It would appear to be possible to unmarshal two different jaxb
objects with the same name.
There is a Bar
class ...
public abstract Bar {
private @XmlElement String val;
}
.. with Two implementations (constructors etc. left out):
@XmlRootElement(name="bar")
public class BarA extends Bar { }
@XmlRootElement(name="bar")
public class BarB extends Bar {
private @XmlElement(required=true) String type;
}
Lastly I want to unmarshall a list of Bar
documents from XML similar to the following
<bars>
<bar>
<val>1</val>
</bar>
<bar>
<val>1</val>
<type>2</type>
</bar>
</bars>
The list is wrapped in an class utilizing the @XmlAnyElement
@XmlRootElement
public class Bars {
@XmlMixed
@XmlAnyElement(lax = true)
@XmlElementRefs({@XmlElementRef(BarA.class), @XmlElementRef(BarB.class)})
private List<Bar> bars;
}
However I seem to only get instances of either BarA
or BarB
, whichever is the last element in the @XmlElementRefs
chain.
Testing code:
String xml = ...
JAXBContext jc = JAXBContext.newInstance(Bars.class);
ByteArrayInputStream in = new ByteArrayInputStream(xml.getBytes());
Bars bars = (Bars) jc.createUnmarshaller().unmarshal(in);
for (Bar bar : bars.getBars()) {
System.out.println(bar.getClass());
}
I don't think the XmlAdapter
suggested in JAXB @XmlElements, different types but same name? would neccesarily be the only approach either.