Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 569
basZero Avatar asked Apr 01 '11 12:04

basZero


People also ask

How do you Unmarshal XML?

To unmarshal an xml string into a JAXB object, you will need to create an Unmarshaller from the JAXBContext, then call the unmarshal() method with a source/reader and the expected root object.

How do you Unmarshal XML to Java object in spring boot?

Spring BOOT is very smart and it can understand what you need with a little help. To make XML marshalling/unmarshalling work you simply need to add annotations @XmlRootElement to class and @XmlElement to fields without getter and target class will be serialized/deserialized automatically.

How does JAXB read XML?

To read XML, first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations. Now get the Unmarshaller instance from JAXBContext . It's unmarshal() method unmarshal XML data from the specified XML and return the resulting content tree.


1 Answers

There is a similar question here.

Is it possible, to just unmarshall by providing Person.class and the unmarshaller finds out itself, whether it has to unmarshall to ReceiverPerson.class or SenderPerson.class?

@XmlRootElement(name="person")
public class ReceiverPerson extends Person {
  // receiver specific code
}

@XmlRootElement(name="person")
public class SenderPerson extends Person {
  // sender specific code (if any)
}

// note: no @XmlRootElement here
public class Person {
  // data model + jaxb annotations here
}
like image 124
basZero Avatar answered Nov 05 '22 08:11

basZero