Java如何在JAXB中定义XML元素顺序?
在此代码段中,您将学习如何定义JAXBAPI生成的XML元素的顺序。要定义元素顺序,我们需要@XmlType在POJO中使用注释。在此注释propOrder中,我们定义了哪个元素应该首先出现,哪个元素应该放在最后。
由生成的XMLmarshaller下面将具有以下顺序:street,city,province,zipCode和country作为最后的XML元素。
package org.nhooo.example.jaxb; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "customerAddress") @XmlType(propOrder = {"street", "city", "province", "zipCode", "country"}) public class Address { private String street; private String city; private String province; private String country; private String zipCode; @XmlElement public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } @XmlElement public String getCity() { return city; } public void setCity(String city) { this.city = city; } @XmlElement public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } @XmlElement public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @XmlElement(name = "postCode") public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } @Override public String toString() { return "Address{" + "street='" + street + ''' + ", city='" + city + ''' + ", province='" + province + ''' + ", country='" + country + ''' + ", zipCode='" + zipCode + ''' + '}'; } }
现在,让我们创建一个程序来运行AddressPOJO的编组过程,以将其转换为XML文档:
package org.nhooo.example.jaxb; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JAXBElementOrder { public static void main(String[] args) { Address address = new Address(); address.setStreet("Sunset Road"); address.setCity("Denpasar"); address.setProvince("Bali"); address.setCountry("Indonesia"); address.setZipCode("800000"); try { JAXBContext context = JAXBContext.newInstance(Address.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(address, System.out); } catch (JAXBException e) { e.printStackTrace(); } } }
它将为您提供以下输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <customerAddress> <street>Sunset Road</street> <city>Denpasar</city> <province>Bali</province> <country>Indonesia</country> <postCode>800000</postCode> </customerAddress>