When marshalling JAXB objects you might get an exception about a missing @XmlRootElement
annotation. For example:
javax.xml.bind.MarshalException - with linked exception:
[com.sun.istack.SAXException2: unable to marshal type "FooType"
as an element because it is missing an @XmlRootElement annotation]
In order to resolve this issue, use the simple
binding mode to generate your JAXB classes.
Create the following binding file:
<jaxb:bindings jaxb:extensionBindingPrefixes="xjc" version="2.1"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc">
<jaxb:globalBindings>
<xjc:simple/>
</jaxb:globalBindings>
</jaxb:bindings>
Pass this file to xjc
or wsdl2java
using the -b
option.
You should now see @XmlRootElement
annotations on your classes.
Alternatively you could wrap your object in an instance of JAXBElement. Generating extra @XmlRootElement annotations into your model will have unintended side effects should you then try to regenerate the XML schema from the generated model.
ReplyDelete- JAXB and Root Elements
It looks like I am having the same problem. In my case, I am using a generic class for marshalling/unmarshalling where method responsible for marshalling takes an Object instance. Also, I have both type of model classes; classes with @XmlRootElement and Classes corresponding to @XmlElementDecl annotations.
DeleteCould you please help me, how can I wrap only the classes with @XmlElementDecl in a instance of JAXBElement and leave rest of them as it is.
Hi Blaise,
ReplyDeleteI had originally taken a look at your approach, but found that I couldn't use it because I'm using a proprietary soap message sender which is a generic class and doesn't allow me to use a JAXBElement.
I wouldn't ever need to regenerate the XML schema from the generated model so it should be ok. Plus, the simple jaxb binding gives me plural property names where applicable.
PS love your work!
Worked like a charm!
ReplyDelete