使用JDK自带的JAXB进行类和xml的互转
Classroom.java
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(); } }
Student.java
import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Student { private int id; private String name; private int age; private Classroom classroom; 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; } public Student() { super(); } }
测试类:TestJaxb.java
import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.junit.Test; public class TestJaxb { @Test /** * 将java对象转成xml */ public void test01() { try { JAXBContext ctx = JAXBContext.newInstance(Student.class); Marshaller marshaller = ctx.createMarshaller(); Student stu = new Student(1,"张三",21,new Classroom(1,"10计算机应用技术",2010)); marshaller.marshal(stu, System.out); } catch (JAXBException e) { e.printStackTrace(); } } @Test /** * 将xml转成java对象 */ public void test02() { try { String xml = "<?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>"; JAXBContext ctx = JAXBContext.newInstance(Student.class); Unmarshaller um = ctx.createUnmarshaller(); Student stu = (Student)um.unmarshal(new StringReader(xml)); System.out.println(stu.getName()+","+stu.getClassroom().getName()); } catch (JAXBException e) { e.printStackTrace(); } } }