简体   繁体   中英

Generate Different types of XMl with same class using JAXB

I have one class:

@XmlRootElement(name="pickup")
public class PickUp 
{
    @XmlAttribute(name="contactName")
    public String contactName;
    @XmlAttribute(name="phoneNumber")
    public String phoneNumber;
    @XmlAttribute(name="pickupDate")
    public String pickupDate;
    @XmlAttribute(name="pickupTime")
    public String pickupTime;
    @XmlAttribute(name="closingTime")
    public String closingTime;
    @XmlAttribute(name="location")
    public String location;
}

This will generate XMl like this:

<Pickup contactName="Test Name" phoneNumber="888-888-8888" pickupDate="2009-08-03" pickupTime="16:30" closingTime="17:45" location="Front Door"/>

This is working perfect, but with same code i also want to generate Xml like below:

<Pickup>
        <contactName>Test Name</contactName>
        <phoneNumber>888-888-8888</phoneNumber>
        <pickupDate>2009-08-03</pickupDate>
        <pickupTime>16:30</pickupTime>
        <closingTime>17:45</closingTime>
        <location>Front Door</location>
</Pickup>

I can do this by creating another class with @xmlElement but i want to use same class for this. Please help me.

I found this https://stackoverflow.com/a/33096124/1976843 answer that can help you.

If you want to keep using jaxb you will need to write your own AnnotationReader

Your are using tags for XML attributes. Use @XmlElement tags to generate the XML in your required format you should give the tags as

@XmlElement  
public String getContactName() {  
    return contactName;  
}  
public void setcontactName(String name) {  
    this.contactName= name;  
}  
@XmlElement  
public String getphoneNumber() {  
    return phoneNumber;  
}  
public void setphoneNumber(String phoneNumber) {  
    this.phoneNumber = phoneNumber;  
}  

No need to create a new class. You can do changes in your original class for xml element.

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