XSD Validation in .NET
It seems like there’s more than one way to do XSD validation in .NET, but only one correct way. Here’s two versions of a chunk of code that does XSD validation on a sitemap file; #define DOCVALIDATE to switch:
#define DOCVALIDATE
using System;
using System.Xml;
using System.IO;
using System.Xml.Schema;namespace XSDValidator
private static void OnValidate(object sender, ValidationEventArgs args) { Console.WriteLine(args.Message); } } }
{ class Program { static void Main(string[] args) { Stream xsdStream = File.OpenRead(args1); XmlDocument sitemapDoc = new XmlDocument(); Stream ms = File.OpenRead(args0); #if DOCVALIDATE XmlSchema xsd = XmlSchema.Read(xsdStream, new System.Xml.Schema.ValidationEventHandler(OnValidate)); sitemapDoc.Schemas.Add(xsd); sitemapDoc.Load(ms); sitemapDoc.Validate(OnValidate); #else XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas.Add(“http://www.google.com/schemas/sitemap/0.84”, XmlReader.Create(xsdStream) ); XmlReader reader = XmlReader.Create(ms, settings); sitemapDoc.Load(reader); #endif }
Going just on the available documents I initially thought it was a simple matter of loading the schema, adding it to the XmlDocument.Schemas collection, and then loading the document, thinking that the ValidationEventHandler handed to XmlSchema.Read would report the errors. It turns out that that particular event handler will only report parse errors on the Schema document itself; you need to call XmlDocument.Validate to actually perform the validation on the document. The second method is a bit less flexible since it requires you to know the targetNamespace a priori, but that specificity could be a good thing; it’s probably better to restrict your options if you’re doing validation as a critical function, as opposed to a generic service.
— Gordon Weakliem
Commenting is closed for this article.