JAXB: unmarshalling xml with multiple names for the same element

可紊 提交于 2019-11-27 23:44:58

问题


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

Basic Question

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

Note: I want to avoid adding another dependency to my project (like MOXy). Ideally, this can be accomplished with annotations or a custom bindings file.

Background

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.

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

Example

input:

<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>

output:

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.

(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)

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


回答1:


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;
}

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


来源:https://stackoverflow.com/questions/11128191/jaxb-unmarshalling-xml-with-multiple-names-for-the-same-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!