使用 JAXB... 您需要为您的 xml 输出生成 xsd。然后您可以从 XSD 生成 JAXB 绑定类。请参见下面的示例。然后使用 JAXB 编组/解组从 xml 获取 bean,反之亦然。有一个例子:http ://www.mkyong.com/java/jaxb-hello-world-example/
输出示例:
<student_list>
<student id="123">
<age>25</age>
<name>Hello Pelo</name>
</student>
<student id="124">
<age>26</age>
<name>Hello Selo</name>
</student>
</student_list>
学生.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="student_list" type="student_listType"/>
<xs:complexType name="student_listType">
<xs:sequence>
<xs:element type="studentType" name="student"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="studentType">
<xs:sequence>
<xs:element type="xs:string" name="age"/>
<xs:element type="xs:string" name="name"/>
</xs:sequence>
<xs:attribute type="xs:string" name="id"/>
</xs:complexType>
</xs:schema>
StudentListType.java
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "student_listType", propOrder = {
"student"
})
public class StudentListType {
@XmlElement(required = true)
protected StudentType student;
/**
* Gets the value of the student property.
*
* @return
* possible object is
* {@link StudentType }
*
*/
public StudentType getStudent() {
return student;
}
/**
* Sets the value of the student property.
*
* @param value
* allowed object is
* {@link StudentType }
*
*/
public void setStudent(StudentType value) {
this.student = value;
}
}
StudentType.java
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "studentType", propOrder = {
"age",
"name"
})
public class StudentType {
@XmlElement(required = true)
protected String age;
@XmlElement(required = true)
protected String name;
@XmlAttribute
protected String id;
/**
* Gets the value of the age property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAge() {
return age;
}
/**
* Sets the value of the age property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAge(String value) {
this.age = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
}