使用JAXB完成java和xml的转化【需要在你的实体类上添加 @XmlRootElement 】
public class Classroom {
privateint id;
privateString name;
privateint grade;
publicClassroom(int id,String name,int grade) {
super();
this.id= id;
this.name= name;
this.grade= grade;
}
publicClassroom() {
super();
//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) {
super();
this.id= id;
this.name= name;
this.age= age;
this.classroom= classroom;
}
publicStudent() {
super();
}
}
@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.f2er.com/xml/295729.html