Java对象和XML之间的编排与反编排

1 创建Java class

1.1 创建Classroom.jave(int id;int grade;String name)
1.2 创建Student.java(int id;String name;int age;Classroom classroom)

2 将Student对象编排成XML

try {
    JAXBContext ctx = JAXBContext.newInstance(Student.class);
    Marshaller marshaller = ctx.createMarshaller();//编排,把对象转换成xml
    Student stu = new Student(1,"Jack",20,new Classroom(1,2012,"Computer"));
    marshaller.marshal(stu, System.out);
} catch (JAXBException e) {
    e.printStackTrace();
}

3 将XML反编排成Student对象

String xml = ""+
            "20"+
            "20121Computer"+
            "1Jack";
try {
    JAXBContext ctx = JAXBContext.newInstance(Student.class);
    Unmarshaller um = ctx.createUnmarshaller();
    Student stu = (Student)um.unmarshal(new StringReader(xml));
    System.out.println("\n"+stu.getName()+","+stu.getClassroom().getName());
} catch (JAXBException e) {
    e.printStackTrace();
}

你可能感兴趣的:(jaxb)