且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何(un)使用JAXB2将列表或数组编组为根元素?

更新时间:2023-10-01 23:05:46

您可以创建一个包含集合的通用列表包装类任何用 @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