deamon
deamon

Reputation: 92367

Mapping a generic, nested XML data structure with JAXB

I'm trying to map the following nested structure to list. The problem is that <list> can be nested. So the top-level list could for example contain one or more other lists which in turn contain some elements like <property> in my example:

<operator name="A2">
    <list name="table">
        <list>
            <property name="A1" value="1" dataType="boolean"/>
            <property name="b" value="1" dataType="boolean"/>
        </list>
    </list>
</operator>

The <list> could also contain <property> elements directly without further nesting:

<operator name="A3">
    <list name="xyz">
        <property name="x" value="1.9" dataType="double"/>
        <property name="y" value="0.2" dataType="double"/>
    </list>
</operator>

I tried to map it like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "list")
public class List<T> {

    @XmlAttribute(name="name")
    public String name;

    @XmlAnyElement
    public T topLevelList;

    public List() {}
}

However, only the outer list gets mapped. This is the relevant fraction from the printed toString call for the first XML block:

Operator{list=List{name='table', topLevelList=[list: null]}}

How can I map such a structure with JAXB?

Upvotes: 1

Views: 574

Answers (1)

Bogdan Samondros
Bogdan Samondros

Reputation: 158

1) @XmlRootElement is not necessary there. Try to put this annotation only in real root elements like Operator in your example.

2) You may not use generic if you sure that List should contain List exactly. Just create two separated fields.

Example of probably solution:

@XmlAccessorType(XmlAccessType.FIELD)
public class List {

    @XmlAttribute(name="name")
    public String name;

    @XmlElement(name = "list")
    public List nestedList;

    @XmlElement(name = "property")
    public List<Property> properties;
...
}

Upvotes: 1

Related Questions