码迷,mamicode.com
首页 > 编程语言 > 详细

Java xml object 互转

时间:2016-02-28 12:33:22      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

 

 

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();
}

Java xml object 互转

标签:

原文地址:http://www.cnblogs.com/catzhou/p/5224295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!