Search code examples
arrayslistjaxbjaxb2

How do I (un)marshall a list or array as the root element with JAXB2?


I would like to marshall and unmarshall documents with JAXB2 annotations that are structured as follows:

<mylist>
  <element />
  <element />
  <element />
</mylist>

It's a well-formed XML document, which represents a sequence of elements.

The obvious thing to do results in a root element of some kind containing the list:

@XmlRootElement(name="container")
public class Container {
    @XmlElement
    @XmlElementWrapper(name="mylist")
    public List<Element> getElements() {...}
}

But then I get a document on marshall with a superfluous root element:

<container>
  <mylist>
    <element />
    <element />
    <element />
  </mylist>
</container>

I'm strugging to work out how to do this with JAXB2 - how do I (un)marshall a list or array that is not contained by another object?


Solution

  • You could create a generic list wrapper class that could contain a collection of any class annotated with @XmlRootElement. When marshalling you can wrap it in an instance of JAXBElement to get the desired root element.

    import java.util.*;
    import javax.xml.bind.annotation.XmlAnyElement;
    
    public class Wrapper<T> {
    
        private List<T> items = new ArrayList<T>();
    
        @XmlAnyElement(lax=true)
        public List<T> getItems() {
            return items;
        }
    
    }
    

    Full Example