问题描述
我想使用JAXB2注释对文档进行编组和解组,其结构如下:
I would like to marshall and unmarshall documents with JAXB2 annotations that are structured as follows:
<mylist>
<element />
<element />
<element />
</mylist>
这是一个格式良好的XML文档,它代表了一系列元素。
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>
我正在努力解决如何使用JAXB2 - 我如何(联合国)编组一个未包含在另一个对象中的列表或数组?
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?
推荐答案
您可以创建一个包含集合的通用列表包装类任何用 @XmlRootElement
注释的类的。编组时,可以将其包装在 JAXBElement
的实例中,以获得所需的根元素。
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;
}
}
完整示例
- Is it possible to programmatically configure JAXB?
- http://blog.bdoughan.com/2012/11/creating-generic-list-wrapper-in-jaxb.html
这篇关于如何(un)使用JAXB2将列表或数组编组为根元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!