Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jaxb2

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>[email protected]</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.

like image 764
Jacomoman Avatar asked Oct 10 '22 14:10

Jacomoman


1 Answers

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

  • http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-moxy-extension.html
  • http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html

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

  • Java/JAXB: Unmarshall Xml to specific subclass based on an attribute
like image 91
bdoughan Avatar answered Oct 14 '22 00:10

bdoughan