JAXB: UnmarshalException: XJC fix for unexpected element, Expected elements are (none).

Caused by: javax.xml.bind.UnmarshalException: unexpected element, Expected elements are (none)

I have a xml that contains a Response element but JAXB could not deserialized it. The stacktrace is below.


Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Response"). Expected elements are (none)
	at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:631)
	at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:236)
	at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:231)
    

It says "Expected elements are (none)" which means that none of the corresponding Java classes in the JAXB context have been annotated by @XmlRootElement.

They should be annotated with something like the


@XmlRootElement(name = "Response")
public class Response {
  ...
    

If this is missing you will get the above exception.

XJC fix

In my case the Java classes are generated by XJC, and the @XmlRootElement is missing because of how the XSD was written.

I changed the element definition so XJC will know it is a root element e.g: before we have

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
	<xs:element name="Response" type="ResponseType">
	<xs:annotation>
		<xs:documentation>Response root element</xs:documentation>
	</xs:annotation>
	</xs:element>
    <xs:complexType name="ResponseType">
	    <xs:sequence>
       ...
      </xs:sequence>
	  </xs:complexType>
	</xs:element>

In this case the element Response is of another complexType called RESPONSEType.

The XSD can be rewritten to make the complexType anonymous. e.g.


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
  <xs:element name="Response">
    <xs:annotation>
      <xs:documentation>Response root element</xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:sequence>
        ....
      </xs:sequence>
    </xs:complexType>
  </xs:element>
    

This will allow XJC to add the missing @XmlRootElement

Published: Saturday, 18 June 2011