JAXB提供了一種把Java object轉(zhuǎn)成XML,或者把XML轉(zhuǎn)成Java object的機制。
JAXB有兩個過程,一個是unmarshalling,另一個是marshalling。
unmarshalling:reading。從XML instance轉(zhuǎn)成Java content。
marshalling:writing。從Java content轉(zhuǎn)成XML instance。
注解的含義
@XmlRootElement 指定了XML document的root element。
@XmlAttribute 指定了root element的attribute。
@XmlElement 指定了root element的sub-element。
object to xml 相關(guān)代碼
try {
JAXBContext jContext = JAXBContext.newInstance(Student.class);
Marshaller marshallObj = jContext.createMarshaller();
marshallObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Student student = new Student("abc", 123, "hadoop");
marshallObj.marshal(student, new FileOutputStream("D:\\student.xml"));
} catch(Exception e) {
e.printStackTrace();
}
xml to object 相關(guān)代碼
try {
JAXBContext jContext = JAXBContext.newInstance(Student.class);
Unmarshaller unmarshallerObj = jContext.createUnmarshaller();
Student student = (Student) unmarshallerObj.unmarshal(JAXB_Demo.class.getClassLoader().getResourceAsStream("config/student.xml"));
System.out.println(student.getName()+":"+student.getId()+":"+student.getSubject());
} catch(Exception e) {
e.printStackTrace();
}