Spotted
Spotted

Reputation: 4091

Improve usage of xsd:any in Java code

I have some legacy XML documents to import in one of my software. The part that causes me some troubles at the moment is the content of the Param element:

Sample.xml

<...>
    <Param>
        <IdNumber>12345678</IdNumber>
        <Factor>12.3</Factor>
        <Date>2015-07-01</Date>
        <Counter unit="1">
            <Medium>1</Medium>
            ...
        </Counter>
        <Counter unit="2">
            <Medium>4</Medium>
            ...
        </Counter>
        ...
    </Param>
</...>

There can be many (number can vary) children elements in Param and to avoid to list all of them in the XSD, this has been declared as follow:

Schema.xsd

...
<xs:element name="Param">
    <xs:complexType>
        <xs:sequence>
            <xs:any minOccurs="0" maxOccurs="unbounded" processContents="skip" />
        </xs:sequence>
    </xs:complexType>
</xs:element>
...

When I use the XJC Tool to generate the one-to-one classes for marshalling/unmarshalling this is what I get:

Param.java

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "any"
})
@XmlRootElement(name = "Param")
public class Param {

    @XmlAnyElement
    protected List<Element> any;

    public List<Element> getAny() {
        if (any == null) {
            any = new ArrayList<Element>();
        }
        return this.any;
    }

}

My problem is that it's not easy to work with the Param class because it only contains an List of Element and need to improve that.

I see 3 solutions:

  1. change nothing
  2. complete the XSD by declaring all the possible elements (and sub-elements) allowing me to have a specific access to each in my Param class.
  3. having a Map instead of a List in Param to simplify searching/extracting elements. Although I don't know how to achieve this and the case with the <Counter unit="1"> and <Counter unit="2"> could be problematic.

So, I'm looking for some advice to choose one of these three solutions OR by proposing another solution.

Upvotes: 1

Views: 329

Answers (1)

Victor
Victor

Reputation: 2546

My opinion;

  • I´d say, if you know what might come 100% sure, option 2 is your choice. However it might be painful to model the XSD.
  • Option 3 seems unfeasible to me, the counter example with depth > 2 is one example.
  • Finally,I have worked in projects where option 1 is taken, and it should be considered as well (you need to write and maintain code but it´s very straighforward to make it work).

Upvotes: 1

Related Questions