4

I have generated java classes using xjc from an xsd where the root element was A of type AType.

The root element generated by jaxb is AType & no class A has been generated.

When I try to unmarshall an xml corresponding to that xsd and cast the JaxbElement it is throwing a cast exception:

Snippet:

JAXBContext jaxbContext = JAXBContext.newInstance(Class.forName("AType"));
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
AType aType = (AType) unmarshaller.unmarshal(new ByteArrayInputStream(xmlString.getBytes()));

Exception:

java.lang.ClassCastException: javax.xml.bind.JAXBElement

Same code for other cases execute properly and successfully deserialize.

How can I find unmarshal() gives me object of what type? I have no clue what's going wrong in this situation, I've tried printing out fields in that jaxbElement but it was not very useful!

Rahul Thakur
  • 882
  • 16
  • 31

2 Answers2

8

If the class of the root element (here: AType) doesn't contain the XmlRootElement-annotation, then the returned root element gets wrapped in a JAXBElement and you have to use its getValue()-method to get the root element.

AFAIK, XJC will only generate the XmlRootElement-annotation if the type of the root element is an anonymous type.

Abdull
  • 26,371
  • 26
  • 130
  • 172
Puce
  • 37,247
  • 13
  • 80
  • 152
  • 1
    FYI - You can also leverage the `JAXBIntrospector` to get the value: http://stackoverflow.com/questions/10243679/when-does-jaxb-unmarshaller-unmarshal-returns-a-jaxbelementmyshemaobject-or-a/10253282#10253282 – bdoughan May 18 '12 at 13:10
1

You can try to do this:

Object o = unmarshaller.unmarshal(...);
System.out.println(o.getClass().getName());
tibtof
  • 7,857
  • 1
  • 32
  • 49
  • 1
    yes, though i knew what will happen, i still did that! `unmarshal()` gives a return of type `JAXBElement` & that's what it prints `javax.xml.bind.JAXBElement` ! – Rahul Thakur May 18 '12 at 12:21
  • Have a look at http://stackoverflow.com/questions/707084/class-cast-exception-when-trying-to-unmarshall-xml, maybe it will help! – tibtof May 18 '12 at 12:25