简体   繁体   中英

Converting Java Object to XML in the order of Schema xml

I have a java object

@XmlRootElement
public class Customer {

    private String name;
    private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>();
    private String id;
    private Date startDate;
    private Date endDate;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @XmlElement(name = "phone-number")
    public List<PhoneNumber> getPhoneNumbers() {
        return phoneNumbers;
    }
    public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }
}

I want to define a schema xml (customer.xsd) which should be used to set the order of tags while generating xml, The Object to xml generated should be like below in different order compared to object members order.

<customer>
    <startDate></startDate>
    <endDate></endDate>
    <name></name>
    <id></id>
    <phoneNumbers></phoneNumbers> 
</customer>

Both the Marshalling and Unmarshalling code should be based on the same schema xml.

Can someone help me how to create this schema and how to achieve my ordering??

You have two choices:

  • In the Java Object you can define @XmlType(propOrder={<order of the elements>}) Refer here for more details.
  • Second approach (Using xsd), you can define a xsd like this:

 <xsd:element name="Customer"> <xsd:complexType > <xsd:sequence> <xsd:element name="name" type="xsd:string" /> <xsd:element name="id" type="xsd:string" /> <xsd:element name="startDate" type="xsd:string" /> <xsd:element name="endDate" type="xsd:int" /> <xsd:element name="phoneNumbers" type="xsd:string" minOccurs="0" maxOccurs="unbounded" /> </xsd:sequence> </xsd:complexType> </xsd:element> 

In the XSD you can order the elements inside the <xsd:sequence> Please note, I have not tried with this XSD for this example, I added it for your reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM