user2187935
user2187935

Reputation: 771

JaxB with lists of complex types

I am fiddling with jaxb, was wondering if someone could tell me what am I doing wrong:

Classes:

@XmlRootElement(name = "zoo")
@XmlAccessorType(XmlAccessType.FIELD)
public class zoo()
{
    @XmlElementWrapper(name = "CATS")
    private List<CatSnapshot> cats;
    // other stuff
}

@XmlAccessorType(XmlAccessType.FIELD)
public class CatSnapshot
{
    @XmlElement
    private Cat cat;
    // some other stuff
}

@XmlAccessorType(XmlAccessType.FIELD)
public class Cat()
{
    // cat stuff
}

Xml result:

<CATS>
    <cats>
        <cat> ... </cat>
    </cats>
    <cats>
        <cat> ... </cat>
    </cats>
    <cats>
        <cat> ... </cat>
    </cats>
</CATS>

now, what bothers me is that every cat is enclosed in cats, I want something like:

<CATS>
<cat> ... </cat>
<cat> ... </cat>
<cat> ... </cat>
</CATS>

What am I doing wrong?

Thank you

Upvotes: 0

Views: 997

Answers (1)

Kenny Tai Huynh
Kenny Tai Huynh

Reputation: 1599

You can use the Zoo with the List<Cat>. Something looks like:

@XmlRootElement(name = "zoo")
@XmlAccessorType(XmlAccessType.FIELD)
public class Zoo
{
    @XmlElementWrapper(name = "CATS")
    private List<Cat> cat = new ArrayList<Cat>();
    // other stuff

    public static void main(String[] args) throws JAXBException {
        Cat cat1 = new Cat();
        Cat cat2 = new Cat();
        Cat cat3 = new Cat();

        Zoo zoo = new Zoo();
        zoo.cat.add(cat1);
        zoo.cat.add(cat2);
        zoo.cat.add(cat3);

        System.out.println(zoo);
        JAXBContext jc = JAXBContext.newInstance(Zoo.class);
        Marshaller marshaller1 = jc.createMarshaller();
        marshaller1.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller1.marshal(zoo, System.out);

    }
}

Result is:

<zoo>
    <CATS>
        <cat/>
        <cat/>
        <cat/>
    </CATS>
</zoo>

Hope this help.

Upvotes: 1

Related Questions