使用java提供的JAXB来实现java到xml之间的转换,先创建两个持久化的类(Student和Classroom):
Classroom:
package com.model; public class Classroom { private int id; private String name; 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 Classroom(){ super(); } public Classroom(int id,String name){ this.id = id; this.name = name;
} }
Student:
import javax.xml.bind.annotation.XmlRootElement; //不要忘记了这个注解@XmlRootElement,说明将Student作为xml的根元素 @XmlRootElement public class Student { private String name; private String sex; private int age; private Classroom classroom; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } 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(){ super(); } public Student(String name,String sex,int age,Classroom classroom){ super(); this.age=age; this.classroom=classroom; this.name = name; this.sex = sex; } }
下面可以建立我的main函数了,在此,我们用的是JAXBContext创建的marshaller与unmarshaller来解析java与xml
package test; 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 com.model.Classroom; import com.model.Student; public class Test { public static void main(String[] args) { //new Test().java_xml();
new Test().xml_java(); } public void java_xml(){ try { JAXBContext jaxbc = JAXBContext.newInstance(Student.class); Marshaller marshaller = jaxbc.createMarshaller(); Student stu = new Student("小瞧","男",22,new Classroom(12,"10级")); //marshaller.setProperty(marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(stu, System.out); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void xml_java(){ String xml = "<?xml version="1.0" encoding="UTF-8" standalone="yes"?>" + "<student><age>22</age>" + "<classroom>" + "<id>12</id>" + "<name>10级</name>" + "</classroom>" + "<name>小瞧</name>" + "<sex>男</sex>" + "</student>"; try { JAXBContext jaxbc = JAXBContext.newInstance(Student.class); Unmarshaller unmar = jaxbc.createUnmarshaller(); Student stu = (Student)unmar.unmarshal(new StringReader(xml)); System.out.println(stu.getAge()); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }