The namespace of element 'Root' must be from the schema namespace, 'http://www.w3.org/2001/XMLSchema'?

10.1k views Asked by At

I have an xml document:

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Child name="MyType" compareMode="EQ"></Child>
</Root>

And I would like to validate this xml with help of the following xsd:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Root">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Child">
          <xs:complexType>
            <xs:attribute name="name" type="xs:string" use="required" />
            <xs:attribute name="compareMode" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

When I try to validate it I receive the following error:

Exception in thread "main" org.xml.sax.SAXException: Validation failed against correct.xml. ErrorMessage:s4s-elt-schema-ns: The namespace of element 'Root' must be from the schema namespace, 'http://www.w3.org/2001/XMLSchema'.

My question is why Root has to be in the namespace of schema? Could that be that I validate the xml document not correctly?

public synchronized boolean isValid(String xmlFragment, File xmlSchema) throws SAXException, IOException{

// 1. Lookup a factory for the W3C XML Schema language

SchemaFactory factory = 
    SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

// 2. Compile the schema. 

Schema schema = factory.newSchema(xmlSchema);

// 3. Get a validator from the schema.
Validator validator = schema.newValidator();

// 4. Parse the document you want to check.
Source source = new StreamSource(new ByteArrayInputStream(xmlFragment.getBytes()));

// 5. Check the document    
    validator.validate(source);        
    return true;
}
2

There are 2 answers

1
Michael Kay On BEST ANSWER

Could it be that xmlSchema holds not the schema you have shown us, but the "schema for schema documents" published by W3C? The error message fragment "ErrorMessage:s4s-elt-schema-ns:" seems to hint at this.

4
TToni On

The document is valid under the defined schema, so it must be something with the code.

The only explicit reference to the wanted namespace (as specified in the error message) is in the SchemaFactory.newInstance call. What happens if you pass an empty ("") namespace there?

Also, it is good style to explicitly set the expected namespace in the XML document in the schema. There are several ways to do this. Since you chose to prefix the XMLSchema-namespace, I would recommend to add xmlns="" targetNamespace="" to your <xs:schema tag.