Reputation: 51
I have the XML:
<?xml version="1.0" encoding="utf-8"?>
<song id="id1"
xmlns="urn:Test:Song:1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:Test:Song:1.0 song.xsd">
<name>name1</name>
</song>
It fails to validate against the XSD:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns="urn:Test:Song:1.0"
targetNamespace="urn:Test:Song:1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema" >
<xs:element name="song">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" minOccurs="0" />
</xs:sequence>
<xs:attribute name="id" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:schema>
in Eclipse and Visual Studio. In Eclipse the error is: cvc-complex-type.2.4.a: Invalid content was found starting with element 'name'. One of '{name}' is expected.
Validation succeeds for the XML:
<?xml version="1.0" encoding="utf-8"?>
<song id="id1"
xmlns="urn:Test:Song:1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:Test:Song:1.0 song.xsd">
<name xmlns="">name1</name>
</song>
The only difference is xmlns="" on the name element. Is there a way to make validation succeed on the first without the use of "no namespace"? What exactly is causing the first XML to fail?
Upvotes: 4
Views: 3730
Reputation: 13966
You need to add elementFormDefault="qualified"
attribute to your schemas <xs:schema>
element.
Only globally defined elements and attributes are automatically in the schemas target namespace. Elements that are defined within a <complexType>
definition are said to be local. Attribute elementFormDefault
defines whether local elements should be qualified or not. For attributes there is attributeFormDefault
attribute.
The default value of these attributes is unqualified
. Therefore in your schema the element <name>
is thought not to have a namespace URI. Usually all elements are desired to be in the target namespace so using elementFormDefault="qualified"
attribute is a common practice. Attributes on the other hand usually should not have a namespace so attributeFormDefault
is often omitted.
More info in the W3C Recommendation http://www.w3.org/TR/xmlschema-0/#ref50
Upvotes: 5