Java xml object 互转

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java xml object 互转相关的知识,希望对你有一定的参考价值。

 

 

public class ClassRoom {
private int id;
private String name;
private int grade;

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 int getGrade() {
return grade;
}

public void setGrade(int grade) {
this.grade = grade;
}

public ClassRoom(int id, String name, int grade) {
super();
this.id = id;
this.name = name;
this.grade = grade;
}

public ClassRoom() {
super();
}

}

 

 

 

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "xml")
public class Student {
private int id;
private String name;
private int age;
private ClassRoom classroom;

@XmlElement(name = "aa")
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 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(int id, String name, int age, ClassRoom classroom) {
super();
this.id = id;
this.name = name;
this.age = age;
this.classroom = classroom;
}

// 无参够着函数一定需要,否则JXBContext无法正常解析。
public Student() {
super();
}
}

 

 

ClassRoom classroom = new ClassRoom(1, "软件工程", 4);
Student student = new Student(101, "张三", 22, classroom);

try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JAXBContext context = JAXBContext.newInstance(Student.class);
Marshaller marshaller = context.createMarshaller();
// 是否格式 化
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "gbk");
// 省略头信息
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(student, baos);
String xmlStr = new String(baos.toByteArray());
System.out.println(xmlStr);

Unmarshaller unmarshaller = context.createUnmarshaller();
student = (Student) unmarshaller.unmarshal(new StringReader(xmlStr));
System.out.println(student.getAge());
System.out.println(student.getClassroom().getName());

} catch (JAXBException e) {
e.printStackTrace();
}

以上是关于Java xml object 互转的主要内容,如果未能解决你的问题,请参考以下文章

Java Json Object 互转

JAVA- Object与Map类型互转

C# list<object>和json互转

jackson:POJO和map互转

JS json对象(Object)和字符串(String)互转方法

JS 对象(Object)和字符串(String)互转