Jaxb XMLRootElement

From Foochal

Jump to: navigation, search


Problem

I got these errors while trying to use JAXB to read an XML file.

[com.sun.istack.SAXException2: unable to marshal type "org.foochal.xmlbindings.FooType" as an element because it is missing an @XmlRootElement annotation]
	at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:304)
	at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:230)
	at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:96)
	at Caused by: com.sun.istack.SAXException2: unable to marshal type "org.foochal.xmlbindings.FooType" as an element because it is missing an @XmlRootElement annotation
	at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:226)
	at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:267)
	at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:472)
	at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:301)
	... 26 more
... Removed 22 stack frames
[com.sun.istack.SAXException2: unable to marshal type "org.foochal.xmlbindings.FooType" as an element because it is missing an @XmlRootElement annotation]
	at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:304)
	at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:230)
	at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:96)
	at 
Caused by: com.sun.istack.SAXException2: unable to marshal type "org.foochal.xmlbindings.FooType" as an element because it is missing an @XmlRootElement annotation
	at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:226)
	at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:267)
	at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:472)
	at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:301)
	... 26 more
... Removed 22 stack frames

Solution

Make sure that the root element is an anonymous complex type and not an instance of a defined type.

Right root element example:

  <xsd:element name="foo">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="bar" type="p:barType" />
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

Wrong root element example:

  <xsd:element name="foo" type="fooType">
  </xsd:element>

  <xsd:complexType name="fooType">
    <xsd:sequence>
      <xsd:element name="bar" type="p:barType" />
    </xsd:sequence>
  </xsd:complexType>

Personal tools