I am trying to parse an XML file using JAXB which contains a list of items. The class of the items depends on the value of an element in the XML.
This is a legacy system and I can't easily change the input format.
For example, given the following XML and class definitions:
<root>
<type>a</type>
<item>
<a>a1</a>
</item>
<item>
<a>a2</a>
</item>
</root>
@XmlRootElement(name = "root")
public class Root {
@XmlElement
String type;
@XmlElement(name="item")
List<Item> items;
}
public class Item {}
public class ItemA extends Item {
@XmlElement
String a;
}
public class ItemB extends Item {
@XmlElement
String b;
}
As it works now, the items list contains two Item objects.
I need the items list in the resulting Root object to contain two ItemA objects, one with a="a1" and the other with a="a2".
If the type element is "b", I need the items list to contain ItemB objects.
There will only be one type element specified in a single XML file.
I have seen several solutions using attribute values, but none using element values.