5

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.

Jacomoman
  • 493
  • 1
  • 6
  • 9

1 Answers1

4

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:

Community
  • 1
  • 1
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Thanks for your answer. Just so I'm clear, are you saying that the reference impl of JAXB2 from Sun/Oracle does not include any feature to make this possible? And that only the MOXy impl has such a feature at this time? – Jacomoman Nov 02 '11 at 17:02
  • @user747821 - That is correct. If you wanted to avoid using any extensions you could potentially use an `XmlAdapter` do to this. To implement it you would need to create an value type that represented all combined properties of the child types. – bdoughan Nov 02 '11 at 17:07
  • @user747821 - Here is an example of the `XmlAdapter` approach: http://stackoverflow.com/questions/3284786/java-jaxb-unmarshall-xml-attributes-to-specific-java-object-attributes/3290816#3290816 – bdoughan Nov 02 '11 at 20:16
  • 1
    Blaise, thanks very much for your answer. You saved me many hours of mucking around. – Jacomoman Nov 04 '11 at 03:06