简体   繁体   中英

XMLSerialization and XML Schema validation

Is it possible to use the XML Schema validation and XMLSerializer together?

My project currently uses XMLSerializer. To validate the schema, we are programatically checking the values like:

if(String.IsNullOrEmpty(person.Name))
   throw new Exception();

Thanks!

You can add some additional checking to the xsd, by using the element restriction element. Each type have some facets that you can apply to the type/element - ranging from simple min/max length to regular expressions.

You can even take it one step further and use the appinfo xsd element, where you can add custom specification for etc. validation checking. This step however require you to parse each xml node individually, as the normal Xml Schema Validation don't trigger appinfo functionality.

As a last resort you can even have a look at Schematron, which is a formalized way to add quite complex validation to your xsd, but it is in itself a bit complex, and in many situations overkill.

I would suggest using the XmlValidatingReader for validatiing the schema. Please see http://www.codeproject.com/KB/XML/Serialization.aspx for an example...

Actually you can just provide an XSD within the XML. When you read it using the XMLSerializer, it will throw exceptions if the XML is not matching the XSD.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM