I have an XML document that looks something like the following:
Note that I cannot change the schema because it is part of a standard XML Schema (Library of Congress METS).
<amdSec ID="AMDSEC001">
<digiprovMD ID="DMD001">
<mdWrap MDTYPE="OBJECT">
<xmlData>
<object xsi:type="file">
.....
</object>
</xmlData>
</mdWrap>
</digiprovMD>
<digiprovMD ID="DMD001_EVENT">
<mdWrap MDTYPE="EVENT">
<xmlData>
<event xsi:type="event">
.....
</event>
</xmlData>
</mdWrap>
</digiprovMD>
</amdSec>
As you can see, the inner element <mdWrap> can contain elements of different types; in this case they’re <event> and <object>, but it isn’t constrained to just those two types. Creating two classes (like below), marshals okay, but this doesn’t work for unmarshalling.
class ObjectMDWrap {
@XmlElementWrapper(name = "xmlData")
@XmlElement(name = "object")
List<MyObject> object; //Wrapped in list to use @XmlElementWrapper
}
class EventMDWrap {
@XmlElementWrapper(name = "xmlData")
@XmlElement(name = "event")
List<MyEvent> event; //Wrapped in list to use @XmlElementWrapper
}
What can I do so that JAXB unmarshals the correct “type” of MDWrap?
I was able to figure out the solution, and it’s much simpler than I initially thought (which speaks to my relative inexperience with XML and JAXB). By creating my
MDWrapclass in the following wayThen
MDWrapcan contain an object of any type, and will unmarshal properly, as long as the class of whichwrappedMDis an instance of is annotated with@XmlRootElement. The trick is to annotatewrappedMDasXmlAnyElement.