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

筅森魡賤 提交于 2019-12-11 07:18:26

问题


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?


回答1:


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

  • Is it possible to programmatically configure JAXB?
  • http://blog.bdoughan.com/2012/11/creating-generic-list-wrapper-in-jaxb.html


来源:https://stackoverflow.com/questions/14505017/how-do-i-unmarshall-a-list-or-array-as-the-root-element-with-jaxb2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!