我希望Java类中的序列化XML输出能够遵循Java类中属性的顺序。
似乎JAXB按字母顺序排序。
我可以通过@XmlType
与propOrder一起使用并指定所有属性来覆盖此属性,但是我有一个包含许多属性的类,而这些属性尚未最终确定。
我读到,指定一个空的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>
感谢您对此的任何帮助。