There are couple of different ways to support this use case if you want to represent it as a single list (see below). You could also represent it as separate lists.
OPTION #1 - Each Element Corresponds to a Unique Class
If each element name in your list corresponds to a different class, then you can use one List
by leveraging @XmlElements
and doing the following:
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement(name = "ROOT")
@XmlAccessorType(XmlAccessType.FIELD)
public class DocumentList {
@XmlElements({
@XmlElement(name="DOCUMENT", type=Document.class),
@XmlElement(name="TEXT", type=Text.class),
@XmlElement(name="ITEM", type=Item.class)
})
private List elements;
}
OPTION #2- Multiple Elements Correspond to the Same Class
If the Class
of the entry in the List
is not enough to uniquely map it to an element, then you are going to need to leverage JAXBElement
to maintain the element information. Note how we have we have removed the @XmlElements
annotation and replaced it with @XmlElementRefs
.
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
@XmlRootElement(name = "ROOT")
@XmlAccessorType(XmlAccessType.FIELD)
public class DocumentList {
@XmlElementRefs({
@XmlElementRef(name="DOCUMENT", type=JAXBElement.class),
@XmlElementRef(name="TEXT", type=JAXBElement.class),
@XmlElementRef(name="ITEM", type=JAXBElement.class)
})
private List elements;
}
Along with the @XmlElementRefs
/@XmlElementRef
annotations we need to provide @XmlElementDecl
annotations on a class annotated with @XmlRegistry
.
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
@XmlRegistry
public class ObjectFactory {
@XmlElementDecl(name="DOCUMENT")
public JAXBElement<String> createDocument(String value) {
return new JAXBElement<String>(new QName("DOCUMENT"), String.class, value);
}
@XmlElementDecl(name="TEXT")
public JAXBElement<String> createText(String value) {
return new JAXBElement<String>(new QName("TEXT"), String.class, value);
}
@XmlElementDecl(name="ITEM")
public JAXBElement<String> createItem(String value) {
return new JAXBElement<String>(new QName("ITEM"), String.class, value);
}
}