Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
543 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...