【工具学习】JAXB - hippowc/hippowc.github.io GitHub Wiki
JAXB, 全称为 Java Architecture for XML Binding, 使用JAXB 注解可以实现java对象和xml相互转换,需要了解三个类:JAXBContext,Unmarshaller,Marshaller,主要使用下面两个方法:
- Marshalling – 转换java对象至xml。
- Unmarshalling – 转换xml至java对象。
JAXB非常容易,首先在java对象上使用注解,然后使用jaxbMarshaller.marshal() 或 jaxbMarshaller.unmarshal()方法实现java对象/xml之间转换。类似这样:
@XmlRootElement
public class Student {...
@XmlAttribute
public String getName() {...
具体使用可以是这样:
//JAXBContext 类提供到 JAXB API 的客户端入口点。它提供了管理实现 JAXB 绑定框架操作所需的 XML/Java 绑定信息的抽象,这些操作包括:解组、编组和验证。
JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);
Student student = new Student("小明", "男", 20);
//Marshaller 类负责管理将 Java 内容树序列化回 XML 数据的过程
Marshaller createMarshaller = jaxbContext.createMarshaller();
createMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
File file = new File("d:\\student123.xml");
if(!file .exists()){
file.createNewFile();
}
createMarshaller.marshal(student,new FileOutputStream(file));
//Unmarshaller 类使客户端应用程序能够将 XML 数据转换为 Java 内容对象树。
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Student student2 = (Student)unmarshaller.unmarshal(file);