我希望我的 Java 类的序列化 XML 输出符合 Java 类中属性的顺序。
似乎 JAXB 按字母顺序排列。
我可以通过使用 propOrder 并指定所有属性来覆盖它@XmlType
,但我有一个包含许多属性的类,这些还没有最终确定。
我读到指定一个空的propOrder会这样做,但事实并非如此。
我的示例类:
package test;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement
//@XmlType(propOrder={"company", "scheme", "agreementNumber"})
@XmlType(propOrder={}) // makes no difference - still alphabetical in XML
public class CustomerPlan2 {
private String company;
private String scheme;
private String agreementNumber;
@XmlElement(name="Company")
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
@XmlElement(name="Scheme")
public String getScheme() {
return scheme;
}
public void setScheme(String scheme) {
this.scheme = scheme;
}
@XmlElement(name="AgreementNumber")
public String getAgreementNumber() {
return agreementNumber;
}
public void setAgreementNumber(String agreementNumber) {
this.agreementNumber = agreementNumber;
}
}
我的序列化代码:
CustomerPlan2 cp2 = new CustomerPlan2();
cp2.setCompany("company");
cp2.setScheme("scheme");
cp2.setAgreementNumber("agreementnumber");
JAXBContext context = JAXBContext.newInstance(CustomerPlan2.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(cp2, new FileWriter("C:\\temp\\out.xml"));
输出:
<customerPlan2>
<AgreementNumber>agreementnumber</AgreementNumber>
<Company>company</Company>
<Scheme>scheme</Scheme>
</customerPlan2>
我希望我的输出是(作为我班级的财产顺序):
<customerPlan2>
<Company>company</Company>
<Scheme>scheme</Scheme>
<AgreementNumber>agreementnumber</AgreementNumber>
</customerPlan2>
感谢您对此的任何帮助。