prev table of contents next

6.2.7.6 Collecting Unspecified Elements: XmlAnyElement

Arbitrary content is indicated by the XML Schema type xsd:anyType. (We have already seen that this corresponds to an object of type org.w3c.dom.Element, cf. subsection DOM Elements.) The annotation XmlAnyElement instructs JAXB to map a field to a DOM Element object, or an array or list of such elements.

Let's say that we want to unmarshal XML data with arbitrary tags and some text content, e,g,:

<document>
  <zoo>
    <a>Anaconda</a>
    <b>Buffalo</b>
    <c>Chameleon</c>
    <d>Dromedar</d>
  </zoo>
</document>
The interesting class is ZooType, defining the structure of the element tagged zoo as a list of DOM elements:
import java.util.*;
import org.w3c.dom.Element;
import javax.xml.bind.annotation.*;

public class ZooType {
    protected List<Element> animals;
    public ZooType(){
    }

    @XmlAnyElement
    public List<Element> getAnimals(){
        if( animals == null ) animals = new ArrayList<Element>();
        return animals;   
    }
    public void setAnimals( List value ){
        animals = value;
    }
}
Unmarshalling and accessing this data is done like this:
JAXBContext jc = JAXBContext.newInstance( DocumentType.class );
Unmarshaller u = jc.createUnmarshaller();
DocumentType doc = (DocumentType)u.unmarshal( f );
for( Element el: doc.getZoo().getAnimals() ){
    System.out.println( el.getNodeName() + "->" +
                        el.getTextContent() );
}
The resulting output looks like this:
a->Anaconda
b->Buffalo
c->Chameleon
d->Dromedar


prev table of contents next