简体   繁体   中英

How to write POJO for Marshalling two list of objects?

<MyRoot>
    <Person>
        <Name>Joe</Name>
        <Age>20</Age>
    </Person>   
    <Address>
        <HouseName>Joe</HouseName>
        <Place>Delhi</Place>
    </Address>
    <Person>
        <Name>James</Name>
        <Age>21</Age>
    </Person>   
    <Address>
        <HouseName>Joe</HouseName>
        <Place>Mumbai</Place>
    </Address>
</MyRoot>

From above xml, you can see that person and address tag is not wrapped in a wrapper tag. I want to generate an xml using JAXB in same format. I don't know how to do that without a wrapper tag.

Are you looking into creating java object that contains a list of Persons and a list of addresses?

public class MyRootObject {
   private List<Person> persons;
   private List<Address> addresses;
}

If the above is what you intend on doing then note that the XML object will change...

If you really want to preserve a mixed sequence like <Person> <Address> <Person> <Address> (as you say in your comment to @Vankuisher's answer), then you need to keep the Person s and Address es not in 2 separate List s, but together within the same List .

For that to work Person and Address must be subclasses of a common superclass (eg class Person extends Item and class Address extends Item ). Then you use an @XmlElements annotation to define the mapping between XML element names and Java classes:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "MyRoot")
public class MyRoot {

    @XmlElements({
        @XmlElement(name = "Address", type = Address.class),
        @XmlElement(name = "Person", type = Person.class)
    })
    private List<Item> items;

    // public getters and setters (omitted here for brevity)
}

When marshalling such a MyRoot object you will get an XML output with the same sequence of items as given within the List<Item> .

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