使用JAXB完成java和xml的转化【需要在你的实体类上添加 @XmlRootElement 】
public class Classroom {
privateint id;
privateString name;
privateint grade;
publicclassroom(int id,String name,int grade) {
this.id= id;
this.name= name;
this.grade= grade;
}
publicclassroom() {
//Todo Auto-generated constructor stub
}
}
@XmlRootElement
public class Student {
privateint id;
privateString name;
privateint age;
private Classroom classroom;
publicStudent(int id,int age,Classroom classroom) {
this.id= id;
this.name= name;
this.age= age;
this.classroom= classroom;
}
publicStudent() {
}
}
@Test【对象转换为XML】
publicvoid test01() {
try{
JAXBContextctx = JAXBContext.newInstance(Student.class);
Marshallermarshaller = ctx.createMarshaller();
Studentstu = new Student(1,"张三",21,new Classroom(1,"10计算机应用技术",2010));
marshaller.marshal(stu,System.out);
}catch (JAXBException e) {
e.printstacktrace();
}
}
@Test【XML转换为对象】
publicvoid test02() {
try{
Stringxml = "<?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>";
JAXBContextctx = JAXBContext.newInstance(Student.class);
Unmarshallerum = ctx.createUnmarshaller();
Studentstu = (Student)um.unmarshal(new StringReader(xml));
System.out.println(stu.getName()+","+stu.getClassroom().getName());
}catch (JAXBException e) {
e.printstacktrace();
}
}
原文地址:https://www.jb51.cc/xml/295729.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。