5

I'm given XML that looks like (lots more attributes of course):

<inventory>
  <item kind="GRILL" tag=123 brand="WEBER"/>
  <item kind="CAR" tag=124 make="FORD" model="EXPLORER" />
</inventory>

with about a dozen different kinds. I am using annotations to map to java classes that look like:

@XmlRootElement(name="inventory")
public class Inventory {
  @XmlElement(name="item")
  public List<Item> itemList = new LinkedList<Item>;
}
abstract public class Item {
  @XmlAttribute public int tag;
}
public class Grill extends Item {
  @XmlAttribute public string brand;
}
public class Car extends Item {
  @XmlAttribute public string make;
  @XmlAttribute public string model;
}

How can I get JAXB to create the sub-classed Item objects based on the "kind" field?

dave
  • 51
  • 1
  • 2
  • possible duplicate of [Java/JAXB: Unmarshall Xml to specific subclass based on an attribute](http://stackoverflow.com/questions/2992234/java-jaxb-unmarshall-xml-to-specific-subclass-based-on-an-attribute) – bdoughan Mar 30 '11 at 23:21
  • you're right...I did a search before posting, but somehow missed it. – dave Mar 30 '11 at 23:34

1 Answers1

4

There area couple of different approaches:

JAXB (JSR-222)

The following approach should work with any JAXB implementation (Metro, MOXy, JaxMe, etc). Use an XmlAdapter where the adapted object contains the properties of the parent class and all the subclasses. In the XmlAdapter add the logic of when a particular subclass should be used. For an example see the link to a similar question below:

EclipseLink JAXB (MOXy)

You could use the @XmlDescriminatorNode extension in EclipseLink JAXB (MOXy) to handle this use case.

Check out my answer to a similar question:

We improved this support in the EclipseLink 2.2 release:

Community
  • 1
  • 1
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Thanks, that's a good answer, but I'll have to get approval from my IT guys to include it in our server platform. – dave Mar 30 '11 at 23:34
  • Meanwhile, are there any examples of doing it in the standard release with an adapter? – dave Mar 30 '11 at 23:35
  • While there is no standard JAXB release (Java SE 6 implementations are just required to provide a JAXB impl), I have updated my answer with an approach that will work with any JAXB implementation. – bdoughan Mar 31 '11 at 01:27