Java Jaxb : unexpected element (uri:"", local:"Create"). Expected elements are <{}Create>

Hann picture Hann · Apr 21, 2014 · Viewed 29.9k times · Source

I have a prob with my JAXB

<element name="create">
    <complexType>
        <sequence>
            <element name="name" type="string"></element>
        </sequence>
    </complexType>
</element>

My xml :

<Create>
<name> coco </name>
</Create>

My code java :

JAXBContext context = JAXBContext.newInstance("MyPackage");
 Unmarshaller decodeur =    context.createUnmarshaller();
System.out.println("text : " + message);
msgObject = decodeur.unmarshal(sr);  
     if (msgObject instanceof Create)

{
      System.out.println(" action");
}

And I have this :

unexpected element (uri:"", local:"Create"). Expected elements are <{http://www.example.org/XSD_Maths}create>

And my Code stoped by this :

 msgObject = decodeur.unmarshal(sr);  

My xml is good ? , Can you help me , because I don't know what's the problem

Answer

bdoughan picture bdoughan · Apr 21, 2014

Your XML Schema probably has a schema tag like the following.

<?xml version="1.0" encoding="UTF-8"?>
<schema 
    xmlns="http://www.w3.org/2001/XMLSchema" 
    targetNamespace="http://www.example.org/XSD_Maths" 
    xmlns:tns="http://www.example.org/XSD_Maths" 
    elementFormDefault="qualified">

Since it specifies a targetNamespace of http://www.example.org/XSD_Maths. Your XML will need to look like the following:

<create xmlns="http://www.example.org/XSD_Maths">
    <name> coco </name>
</create>

Note About Unmarshalling from a DOM

If you unmarshalling from a DOM Document or Element make sure that the DOM parser you used was namespace aware. This is done by setting the following flag on the DocumentBuilderFactory.

documentBuilderFactory.setNamespaceAware(true);

For More Information

Below is a link to an article on my blog where I go into more depth about JAXB and namespaces.