JAXB编组泛型列表可变根元素名称 [英] JAXB Marshalling generic list with variable root element name

查看:1639
本文介绍了JAXB编组泛型列表可变根元素名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图获取对象的泛型列表,但我想每个列表有一个特定的XmlRootElement将(​​名字..)。我做的方式,我知道这不是真的有可能无需编写特定的包装类每种类型的对象,并宣布XmlRootElement将。但也许有另一种方式...?

So I'm trying to marshal a generic list of objects, but i want each list to have a specific XmlRootElement(name..). The way I'm doing it, I know it's not really possible without writing a specific wrapper class for each type of object and declaring the XmlRootElement. But maybe there's another way...?

考虑如下的类:

abstract public class Entity {

}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="user")
public class User extends Entity {

    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername( String username ) {
        this.username = username;
    }

}

@XmlRootElement
public class EntityList<T extends Entity> {

    @XmlAnyElement(lax=true)
    private List<T> list = new ArrayList<T>();

    public void add( T entity ) {
        list.add( entity );
    }

    public List<T> getList() {
        return list;
    }

}


public class Test {

    public static void main( String[] args ) throws JAXBException {

        User user1 = new User();
        user1.setUsername( "user1" );

        User user2 = new User();
        user2.setUsername( "user2" );

        EntityList<User> list = new EntityList<User>();
        list.add( user1 );
        list.add( user2 );

        JAXBContext jc = JAXBContext.newInstance( EntityList.class, User.class );
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal( list, System.out );
   }

}

正如预期的那样,这将产生:

As expected, this produces:

<entityList>
    <user>
        <username>user1</username>
    </user>
    <user>
        <username>user2</username>
    </user>
</entityList>

我要的是能够修改标签名,这取决于我创建一个EntityList实体的类型。

What i want is to be able to modify that tag name, depending on the type of Entity i create the EntityList with.

我知道我们谈论编译VS运行时间在这里,但也许有某种哈克的方式来改变从孩子的父元素包装?

I know we're talking compile vs run time here, but maybe there's some kind of hacky way to change the parent element wrapper from the child?

推荐答案

您可以包装EntityList的实例中的JAXBElement在运行时提供了根元素名称。

You can wrap the instance of EntityList in a JAXBElement to provide a root element name at runtime.

示例

  • http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted/TheBasics

这篇关于JAXB编组泛型列表可变根元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆