JAXB:为同一元素解组具有多个名称的 xml

2022-01-19 00:00:00 xml binding java jaxb unmarshalling

我认为这对于真正了解 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<Employees>员工,其中每个员工只有一个名字和姓氏.

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?

推荐答案

这对应一个choice结构.您可以为此用例使用 @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:

  • http://blog.bdoughan.com/2011/04/xml-schema-to-java-xsd-choice.html

相关文章