7

I have a problem 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 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 stopped at this line:

 msgObject = decodeur.unmarshal(sr);  

Is my XML OK or is there a problem with it? I'm not sure why I'm getting this error.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Hann
  • 727
  • 3
  • 11
  • 22
  • Your XML has "Create" with uppercase "C" and your schema has "create" with a lowercase "c". Typo in your question, or typo in the code? – Rob Apr 21 '14 at 20:36

1 Answers1

18

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.

bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Tahnks Blaise , I have the same schema but your xml is not working – Hann Apr 21 '14 at 20:27
  • @user3557873 - Do you get a different exception? – bdoughan Apr 21 '14 at 20:29
  • @user3557873 - What type of object is your `sr` variable holding onto. – bdoughan Apr 21 '14 at 20:34
  • 1
    Thanks so muuccccch Blaise , I retstart my Eclipse and it's working with your xml. Blaise you're great :) thanks thanks – Hann Apr 21 '14 at 20:44
  • @bdoughan I have a similar problem. Can you have a look at it https://stackoverflow.com/questions/67975111/xmlstreamexception-xmlns-has-been-already-bound-to-rebinding-it-to-http-deu – truekiller Jun 15 '21 at 09:41