具有可变根元素名称的 JAXB 编组通用列表 [英] JAXB Marshalling generic list with variable root element name

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

问题描述

所以我试图编组一个通用的对象列表,但我希望每个列表都有一个特定的 XmlRootElement(name..).我这样做的方式,我知道如果不为每种类型的对象编写特定的包装类并声明 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.

我知道我们在这里谈论的是编译与运行时间,但也许有某种方法可以从子元素更改父元素包装器?

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.

示例

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

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