Search code examples
javajaxbjaxb2moxy

JAXB 2.x: How to unmarshal an XML without knowing the target class?


If there is a way, how to do this, I'd like to know the most elegant one. Here is the question: - Let's assume you have an abstract class Z - You have two classes inherited from Z: named A and B.

You marshal any instance (A or B) like this:

JAXBContext context = JAXBContext.newInstance(Z.class);
Marshaller m = context.createMarshaller();
m.marshal(jaxbObject, ...an outputstream...);

In the resulting XML you see what kind of instance it was (A or B).

Now, how do you unmarshall like

JAXBContext jc = JAXBContext.newInstance(Z.class);
Unmarshaller u = jc.createUnmarshaller();
u.unmarshal(...an inputstream...)

I get an UnmarshalException saying

"Exception Description: A descriptor with default root element {<my namespace>}<the root tag, e.g. A or B> was not found in the project]

javax.xml.bind.UnmarshalException"

So how do you do unmarshalling so that you get an instance of Z and then you can test AFTER unmarshalling, what it is? e.g. z instanceof A then... z instanceof B then something else... etc.

Thanks for any ideas or solutions.

I am using JRE1.6 with MOXy as JAXB Impl.


Solution

  • THERE IS NO SOLUTION TO MY QUESTION!

    Under any circumstances you have to tell the unmarshaller exactly what object it should unmarshall to.