July 11, 2006

How to validate XSLT output in .NET 2.0

How would you validate XSLT output on the fly without caching transformation result as a whole? That's easy - just use MvpXslTransform class that adds to the XslCompiledTransform class ability to transform into XmlReader and wrap that reader witth a validating reader. As a result - streaming validation, no memory hogging and ability to abort transformation at first validation error. Simple sample below.

XPathDocument doc = 
    new XPathDocument("source.xml");
MvpXslTransform xslt = new MvpXslTransform();
XmlReader resultReader = 
    xslt.Transform(new XmlInput(doc), null);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add("", "orders.xsd");
XmlReader validatingReader = 
    XmlReader.Create(resultReader, settings);
XmlWriter w = XmlWriter.Create(Console.Out);
w.WriteNode(validatingReader, false);

You can get MvpXslTransform class with Mvp.Xml library v2.0 at the Mvp.Xml project site.