How to Have Mixed XML Elements in a Single List (Choice)
It is possible to put different XML elements in the same list. Let's say you want to create a collection of values that can either be strings, numbers or a key/value pair of strings. This can be represented by the following schema:
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="values">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="aString" type="xs:string"/>
<xs:element name="aNumber" type="xs:int"/>
<xs:element name="aKeyValuePair">
<xs:complexType>
<xs:sequence/>
<xs:attribute name="key" type="xs:string"/>
<xs:attribute name="value" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
The problem here is that the aString, aNumber and aKeyValuePair elements do not have a common super-class. You can implement it in Java by using an Object collection and specifying all possible types that the collection may contain:
@XmlRootElement(name="values")
@XmlType(name="") // anonymous (inline) type
public class Values {
@XmlElements({ // declares the element choice
@XmlElement(name="aKeyValuePair", type=Values.AKeyValuePair.class),
@XmlElement(name="aString", type=String.class),
@XmlElement(name="empty")
})
public List<Object> list = new new ArrayList<Object>();
@XmlType(name="") // anonymous (inline) type
public static class AKeyValuePair {
@XmlAttribute
public String key;
@XmlAttribute
public String value;
}
}

