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();
}
}
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "xml")
public class Student {
private int id;
private String name;
private int age;
private ClassRoom classroom;
@XmlElement(name = "aa")
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;
}
// 无参够着函数一定需要,否则JXBContext无法正常解析。
public Student() {
super();
}
}
ClassRoom classroom = new ClassRoom(1, "软件工程", 4);
Student student = new Student(101, "张三", 22, classroom);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JAXBContext context = JAXBContext.newInstance(Student.class);
Marshaller marshaller = context.createMarshaller();
// 是否格式 化
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "gbk");
// 省略头信息
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(student, baos);
String xmlStr = new String(baos.toByteArray());
System.out.println(xmlStr);
Unmarshaller unmarshaller = context.createUnmarshaller();
student = (Student) unmarshaller.unmarshal(new StringReader(xmlStr));
System.out.println(student.getAge());
System.out.println(student.getClassroom().getName());
} catch (JAXBException e) {
e.printStackTrace();
}