JAXB:解组有多个名字的XML为同一元素 [英] JAXB: unmarshalling xml with multiple names for the same element

查看:161
本文介绍了JAXB:解组有多个名字的XML为同一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这将是很容易的人谁真正了解JAXB绑定文件...

I figure this will be easy for someone who really understands JAXB binding files...

如何配置JAXB到多个元素解组到同一类?

How do you configure JAXB to unmarshal multiple elements into the same class?

注:我想避免添加其他依赖于我的项目(​​如莫西)。理想情况下,可以用注释或自定义绑定文件来完成。

我有一个包含很多相同的元件的变型的一个XML文档 - 每个具有完全相同的特性。使用下面我举的例子,我所关心的是员工,但XML规定董事,经理和工作人员。对于我们来说,这些都是同一母公司的子类,我们只需要与父类型(员工)和我们的对象模型的工作不具备或需要的子类的实例。

I have an XML document that contains lots of variations of the same element--each with the exact same properties. Using my example below, all I care about is "Employees" but the XML specifies "directors, managers and staff." For our purposes, these are all subclasses of the same parent and we only need to work with the parent type (Employee) and our object model doesn't have or need instances of the subclasses.

我要JAXB绑定的任何实例董事,经理或工作人员元素到员工对象。

I want JAXB to bind any instance of director, manager, or staff elements into an Employee object.

输入:

<organization>
    <director>
        <fname>Dan</fname>
        <lname>Schman</lname>
    </director>    
    <manager>
        <fname>Joe</fname>
        <lname>Schmo</lname>
    </manager>    
    <staff>
        <fname>Ron</fname>
        <lname>Schwan</lname>
    </staff>    
    <staff>
        <fname>Jim</fname>
        <lname>Schwim</lname>
    </staff>    
    <staff>
        <fname>Jon</fname>
        <lname>Schwon</lname>
    </staff>    
</organization>

输出:

解组这个例子后,我最终会得到一个属性的组织对象:列表&LT;员工与GT;员工,其中每个员工只有一个firstName和lastName。

After unmarshalling this example, I would end up with an Organization object with one property: List<Employees> employees where each employee only has a firstName and lastName.

(注:每位员工将类型员工不是总监/经理/员工子类的信息会失去了解组时,我们也不在乎编组退了出来 - 我们只需要创建一个XML对象)

(Note: each employee would be of type Employee NOT Director/Manager/Staff. Subclass information would be lost when unmarshalling. We also don't care about marshaling back out--we only need to create objects from XML)

可以这样不喜欢MOXY扩展做了什么?自定义bindings.xjb文件可以保存一天?

Can this be done without extensions like MOXy? Can a custom bindings.xjb file save the day?

推荐答案

这相当于一个选择结构。你可以使用 @XmlElements 标注对这种用例:

This corresponds to a choice structure. You could use an @XmlElements annotation for this use case:

@XmlElements({
    @XmlElement(name="director", type=Employee.class),
    @XmlElement(name="manager", type=Employee.class)
})
List<Employee> getEmployees() {
    return employees;
}

如果您是从XML模式开始下面会有所帮助:

If you are starting from an XML schema the following will help:

这篇关于JAXB:解组有多个名字的XML为同一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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