Reputation: 21
I am currently trying to unmarshal an XML document via JAXB. I've already have generated the JAXB classes within my project, and have a root class annotated with @XmlRootElement.
Unfortunately, when I attempt to unmarshal, I receive the following exception:
java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast to a.b.Foo
My Foo class has the proper annotation, and as far as I'm aware, this should be able to unmarshal my XML into the Foo class.
Any thoughts on what could cause this?
Edit (for clarification): The call I'm attempting to make to unmarshal is this:
Foo foo = (Foo)unmarshaller.unmarshal(input);
Second Update I'm not allowed to update our schema, but below is the XML schema structure to the 'Foo' element...
<xsd:element name="Foo" type="Foo_Type"/>
<xsd:complexType name="Foo_Type">
<!-- more schema definition here -->
</xsd:complexType>
I am then adding the @XmlRootElement annotatino to the Foo class via JAXB Bindings. I've found that if I change the schema to be like so:
<xsd:element name="Foo">
<xsd:complexType>
<!-- more schema definition here -->
</xsd:complexType>
</xsd:element>
Everything works fine, but once again -- we're not supposed to be updating the schema.
Upvotes: 2
Views: 905
Reputation: 149017
A class with an @XmlRootElement
annotation should only be unmarshalled to an instance of JAXBElement
if one of the unmarshal
methods that takes a Class
parameter is used.
If your unmarshal code is the following:
Foo foo = (Foo)unmarshaller.unmarshal(input);
Then you must have an @XmlElementDecl
on a class annotated with @XmlRegistry
(by default this class is called ObjectFactory
when the model is generated from an XML Schema) corresponding to the Foo
class. I have written more about this on my blog:
Upvotes: 1