Marshal
UnMarshal
创建 Java实体类
/**
* @XmlRootElement
* 该注解将 类 映射为 XML全局对象
*/
@XmlRootElement
public class Student {
private String id;
private String name;
private Integer age;
public Student() {
}
public Student(String id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试类
public class TestJAXB {
@Test
public void test01() throws JAXBException {
Student student = new Student("1", "hjx", 24);
// 获取 JAXB 的上下文环境,要求传入具体的 Bean
JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);
// 创建 Marshaller 实例,用于将 java类转换为 XML文档
Marshaller marshaller = jaxbContext.createMarshaller();
// 参数1:需要转换的Java类实例,
// 参数2:输出位置,System.out 打印到控制台
marshaller.marshal(student,System.out);
}
}
运行结果
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><student><age>24</age><id>1</id><name>hjx</name></student>
注意事项
JAXBElement
类型,或者使用 @XmlRootElement
注解在resources文件夹下创建 test.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student>
<age>22</age>
<id>2</id>
<name>zs</name>
</student>
测试类
@Test
public void test02() throws JAXBException {
// 获取 JAXB 的上下文环境,要求传入具体的 Bean
JAXBContext context = JAXBContext.newInstance(Student.class);
// 创建 UnMarshaller 实例
Unmarshaller unmarshaller = context.createUnmarshaller();
// 加载需要转换的XML数据 -> 这里使用InputStream,还可以使用File,Reader等
InputStream stream = Student.class.getClassLoader().getResourceAsStream("test.xml");
// 将XML数据序列化 -> 该方法的返回值为Object基类,需要强转类型
Student stu = (Student) unmarshaller.unmarshal(stream);
// 将结果打印到控制台
System.out.println(stu);
}
运行结果
Student{id='2', name='zs', age=22}