JAXB提供了一种把Java object转成XML,或者把XML转成Java object的机制。
JAXB有两个过程,一个是unmarshalling,另一个是marshalling。
unmarshalling:reading。从XML instance转成Java content。
marshalling:writing。从Java content转成XML instance。
注解的含义
@XmlRootElement 指定了XML document的root element。
@XmlAttribute 指定了root element的attribute。
@XmlElement 指定了root element的sub-element。
object to xml 相关代码
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 相关代码
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();
}