开发者

How to do simple XML schema validation with no namespaces in C#

I have generated a set of classes using xsd.exe and created an XML document from the resulting generated code. I would now like to validate the serialized class instance against the original xsd.

My XML is like this:

<?xml version="1.0" encoding="UTF-8"?>
<MyRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   -- rest of XML document here
</MyRoot>

My XSD is like this:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <xs:element name="MyRoot" type="MyRootType"/>开发者_开发问答
   -- MyRootType definition and rest of XSD
</xs:schema>

When I try to validate the XML using a XmlReader, I get the following error: "The 'MyRoot' element is not declared."

What could be wrong?


In your MyRoot element, you need to add the location of the XSD. I would also recommend defining the namespace (unless you have good reason not to).

<api:MyRoot  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
   xmlns:api='http://www.myserver.com/schema'
   xsi:schemaLocation='http://www.myserver.com/schema http://www.myserver.com/schema/websuiterecord.xsd'>
</api:MyRoot>

This way, the validation tool knows where to find your XSD to validate your XML against.


The approach was correct, but the XSD was not infact being read. I corrected this and it worked as expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜