JAXB:使用同一元素的多个名称解组 xml [英] JAXB: unmarshalling xml with multiple names for the same element

查看:33
本文介绍了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?

注意:我想避免向我的项目添加另一个依赖项(如 MOXy).理想情况下,这可以通过注释或自定义绑定文件来完成.

我有一个 XML 文档,其中包含相同元素的许多变体——每个变体都具有完全相同的属性.使用下面的示例,我只关心员工",但 XML 指定了董事、经理和员工".对于我们的目的,这些都是同一个父类的子类,我们只需要使用父类型 (Employee) 并且我们的对象模型没有或不需要子类的实例.

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 将 director、manager 或 staff 元素的任何实例绑定到 Employee 对象中.

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>

输出:

解组这个例子后,我会得到一个 Organization 对象,它有一个属性:List;员工,其中每个员工只有一个名字和姓氏.

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.

(注意:每个员工的类型都是Employee而不是Director/Manager/Staff.解组时子类信息会丢失.我们也不关心编组退出——我们只需要从 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天全站免登陆