XmlSchemaValidationException: item 'B' not declared

I am using XmlReader to validate Xml on Xsd.

When I check this xml

<?xml version="1.0" encoding="utf-8" ?> <A><B>sdf</B></A> 

regarding this scheme:

 <?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 check.

But if I add a namespace:

 <?xml version="1.0" encoding="utf-8" ?> <A xmlns="myns"><B>sdf</B></A> 

and corresponding scheme:

 <?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: element 'B' is not declared. Why is this happening? And how can I add a namespace?

+4
source share
1 answer

The reason you get a validation error is because your schema is actually two schemas. You have two root elements: A and B. The root element cannot be implicitly used as a type. You need to tell XSD that you want to use types from another schema (using imports) or make these types local to the schema (using the complexType definition).

Example : Extract B into your own schema. It cannot use the same namespace:

 <?xml version="1.0" encoding="utf-8"?> <xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="myns2"> <xs:element name="B" type="xs:string" /> </xs:schema> 

You can then reference B from your type A using import:

 <?xml version="1.0" encoding="utf-8"?> <xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="myns" xmlns:myns2="myns2"> <xs:import namespace="myns2" /> <xs:element name="A"> <xs:complexType> <xs:sequence> <xs:element ref="myns2:B" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> 

This allows you to have the following valid instance of XML:

 <?xml version="1.0" encoding="utf-8" ?> <A xmlns="myns"> <B xmlns="myns2">sdf</B> </A> 

The reason you were able to check versions of types other than namespace'd was because for proper XML two things must be true:

  • Well-formed XML
  • Must match any reference schema types

An XML file other than a namespace does not, by definition, reference any type of schema, so the document is valid XML.

+5
source

Source: https://habr.com/ru/post/1389617/


All Articles