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

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

Published: Saturday, 18 June 2011
java ws jaxb

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

An xml document contains a Response element that JAXB could not deserialize. 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

If the Java classes were generated by XJC, and the @XmlRootElement is missing due of how the XSD was written, then changed the element definition so XJC will know it is a root element e.g: before we had

<?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>
</xs:schema>

This will allow XJC to add the missing @XmlRootElement.