【发布时间】:2015-01-24 14:24:09
【问题描述】:
我正在尝试通过 JAXB 从 Java 对象生成 XML 文件。我有以下 Java 类:
@XmlRootElement
public class StudentsInfo {
String university;
String faculty;
long facultyNumber;
int degree;
String specialty;
public String getUniversity() {
return university;
}
@XmlElement
public void setUniversity(String university) {
this.university = university;
}
public String getFaculty() {
return faculty;
}
@XmlElement
public void setFaculty(String faculty) {
this.faculty = faculty;
}
public long getFacultyNumber() {
return facultyNumber;
}
@XmlElement
public void setFacultyNumber(long facultyNumber) {
this.facultyNumber = facultyNumber;
}
public int getDegree() {
return degree;
}
@XmlElement
public void setDegree(int degree) {
this.degree = degree;
}
public String getSpecialty() {
return specialty;
}
@XmlElement
public void setSpecialty(String specialty) {
this.specialty = specialty;
}
}
然后在其他类中使用 main() 方法我这样做:
StudentsInfo studentsInfo = new StudentsInfo();
studentsInfo.setFaculty("university name");
studentsInfo.setFaculty("faculty name");
studentsInfo.setFacultyNumber(1234);
studentsInfo.setDegree(1);
studentsInfo.setSpecialty("specialty name");
// create an XML from studentsInfo
try {
JAXBContext jaxbContext = JAXBContext.newInstance(StudentsInfo.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(studentsInfo, sw);
String stringXML = sw.toString();
System.out.println(stringXML);
} catch (JAXBException e) { e.printStackTrace(); }
所以 JAXB 生成以下 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<studentsInfo>
<degree>1</degree>
<faculty>faculty name</faculty>
<facultyNumber>1234</facultyNumber>
<specialty>specialty name</specialty>
<university>university name</university>
</studentsInfo>
但实际上我希望它生成具有另一个层次结构的 XML - 我想从某些字段中创建嵌套的 XML 标记,例如:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<studentsInfo>
<!-- I want to have some nested elements like these for example: -->
<university name="university name">
<faculty>faculty name</faculty>
<facultyNumber>1234</facultyNumber>
<specialty>specialty name</specialty>
</university>
<degree>1</degree>
</studentsInfo>
那么有没有办法做到这一点,而不必创建新的 Java 类和子类?因为真正的代码比这长得多,字段也多,我不能一开始就重写..
【问题讨论】:
标签: java xml jaxb xml-serialization marshalling