Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB: unmarshalling xml with multiple names for the same element

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?

like image 370
gMale Avatar asked Jun 20 '12 21:06

gMale


1 Answers

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
like image 127
bdoughan Avatar answered Sep 29 '22 06:09

bdoughan