Jerry Nixon on Windows: Validate XML/XSD using XmlReaderSettings

Jerry Nixon on Windows

Tuesday, December 9, 2008

Validate XML/XSD using XmlReaderSettings

In the .Net Framework 3.5, the XmlValidationReader was deprecated changing the syntax used to validate XML against an XSD schema. If you use it you will get this message: "Use XmlReader created by XmlReader.Create() method using appropriate XmlReaderSettings instead.".


I put together a simple reusable method to demonstrate the new approach.


using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Schema;

/// <summary>
/// Validate XML against XSD
/// </summary>
/// <param name="xml">raw XML string</param>
/// <param name="xsd">raw XSD string</param>
/// <returns>bool validation result</returns>
static bool ValidateXml(string xml, string xsd)
// build XSD schema

StringReader _XsdStream;
_XsdStream = new StringReader(xsd);

XmlSchema _XmlSchema;
_XmlSchema = XmlSchema.Read(_XsdStream, null);

// build settings (this replaces XmlValidatingReader)

XmlReaderSettings _XmlReaderSettings;
_XmlReaderSettings = new XmlReaderSettings()
ValidationType = ValidationType.Schema

// build XML reader

StringReader _XmlStream;
_XmlStream = new StringReader(xml);

XmlReader _XmlReader;
_XmlReader = XmlReader.Create(_XmlStream, _XmlReaderSettings);

// validate

using (_XmlReader)
while (_XmlReader.Read())

// validation succeeded

return true;
// validation failed

return false;