I’m using XmlReader to validate Xml against Xsd.
When I validate this xml
<?xml version="1.0" encoding="utf-8" ?>
<A><B>sdf</B></A>
against this schema:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="B" type="xs:string" />
<xs:element name="A">
<xs:complexType>
<xs:sequence>
<xs:element ref="B"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
validation is OK.
But if I add namespace:
<?xml version="1.0" encoding="utf-8" ?>
<A xmlns="myns"><B>sdf</B></A>
and corresponding schema:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="myns">
<xs:element name="B" type="xs:string" />
<xs:element name="A">
<xs:complexType>
<xs:sequence>
<xs:element ref="B"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
I accept System.Xml.Schema.XmlSchemaValidationException: The ‘B’ element is not declared.
Why this happens? And how can I add a namespace?
The reason you are getting the validation error is that your schema is actually two schemas. You have two root elements, A and B. A root element cannot be implicitly used as a type. You need to tell XSD that you want to use types from another schema (using an import), or make those types local to the schema (using a complexType definition).
Example: extract B out into it’s own schema. It cannot share the same namespace:
Then you can reference B from your A type by using import:
This allows you to have the following valid XML instance:
The reason you were able to validate the non-namespace’d versions of the types was because in order to be valid XML two things need to be true:
In the non-namespace’d XML file, there is by definition no reference to any schema types, so therefore the document is valid XML.