简体   繁体   中英

JAXB: Unmarshall to different classes based on an element's attribute value

I'd like to know if there's any way to unmarshall XML that contains a fixed element name whose attribute refers to a variety of classes. Consider the following XML:

Case #1:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <request-status>valid</request-status>
    <interface name="person">
        <f-name>Joe</f-name>
        <l-name>Blow</l-name>
        <age>25</age>
        <email>joe.blow@email.com</email>
    </interface>
</response>

Case #2:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <request-status>valid</request-status>
    <interface name="vehicle">
        <make>Ford</make>
        <type>truck</type>
        <year>1989</year>
        <model>F150</model>
    </interface>
</response>

In both cases, the containing class is "response", with 2 instance variables: requestStatus (String), and interface (some superclass?). What I need help with is how to write the containing class "Response" with the correct JAXB annotations so that the unmarshall will create the correct class instances for the "interface" variable.

Thanks a bunch in advance for any help.

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.

You could use MOXy's @XmlDescriminatorNode / @XmlDescriminatorValue JAXB extension.

Base

@XmlDiscriminatorNode("@name")
public abstract class Base {
}

Person

@XmlDiscriminatorValue("person")
public class Person extends Base {
}

Vehicle

@XmlDiscriminatorValue("vehicle")
public class Vehicle extends Base {
}     

For More Information

Below is an answer to a similar question that uses an older version of the MOXy API:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM