java学习

java学习

 

使用jaxb完成对象和xml的转换

学生类

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Student {
 private int id;
 private String name;
 private int age;
 private Classroom classroom;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public Classroom getClassroom() {
  return classroom;
 }
 public void setClassroom(Classroom classroom) {
  this.classroom = classroom;
 }
 public Student(int id, String name, int age, Classroom classroom) {
  super();
  this.id = id;
  this.name = name;
  this.age = age;
  this.classroom = classroom;
 }
 public Student() {
  super();
 }
 
 
}

教室类
public class Classroom {
 private int id;
 private String name;
 private int grade;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getGrade() {
  return grade;
 }
 public void setGrade(int grade) {
  this.grade = grade;
 }
 public Classroom(int id, String name, int grade) {
  super();
  this.id = id;
  this.name = name;
  this.grade = grade;
 }
 public Classroom() {
  super();
  // TODO Auto-generated constructor stub
 }
 
 
}

测试类:

public class TestJaxb {

    public static void main(String[] args){
        TestJaxb.test02();
    }
 @Test
 public static void test01() {//测试对象转换xml字符串
  try {
   JAXBContext ctx = JAXBContext.newInstance(Student.class);
   Marshaller marshaller = ctx.createMarshaller();
   Student stu = new Student(1,"张三",21,new Classroom(1,"10计算机应用技术",2010));
   marshaller.marshal(stu, System.out);
  } catch (JAXBException e) {
   e.printStackTrace();
  }
 }
 
 @Test
 public static void test02() {//测试xml字符串转换对象
  try {
   String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>21</age><classroom><grade>2010</grade><id>1</id><name>10计算机应用技术</name></classroom><id>1</id><name>张三</name></student>";
   JAXBContext ctx = JAXBContext.newInstance(Student.class);
   Unmarshaller um = ctx.createUnmarshaller();
   Student stu = (Student)um.unmarshal(new StringReader(xml));
   System.out.println(stu.getName()+","+stu.getClassroom().getName());
  } catch (JAXBException e) {
   e.printStackTrace();
  }
  
 }
}


posted on 2013-08-07 11:02 杨军威 阅读(857) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜