第一步,Classroom类:Classroom.java
package com.test.jaxb;
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();
}
}
第二步,Student类:Student.java
package com.test.jaxb;
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();
}
}
编写两个测试方法测试jaxb编排和反编排Student对象
TestJaxb.java
package com.test.jaxb;
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.junit.Test;
public class TestJaxb {
@Test
public void test01() {
try {
JAXBContext ctx = JAXBContext.newInstance(Student.class);
Marshaller marshaller = ctx.createMarshaller();
Student stu = new Student(1,"张三",21,new Classroom(1,"计算机科学与技术",2010));
marshaller.marshal(stu, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
@Test
public void test02() {
try {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>21</age><classroom><grade>2010</grade><id>1</id><name>计算机科学与技术</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();
}
}
}
注意:
1.编排和反编排对象的时候,要用注解@XmlRootElement指明对象是根节点
2.如果Student类或Classroom类中没有默认的构造器,会出下错误信息:
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
com.test.jaxb.Student does not have a no-arg default constructor.
this problem is related to the following location:
at com.test.jaxb.Student
因为通过Student类生成JAXBContext对象时,要用到它的默认构造器。