Jerry Nixon @Work: 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. http://go.microsoft.com/fwlink/?linkid=14202".

 

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)
{
try
{
// 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
};
_XmlReaderSettings.Schemas.Add(_XmlSchema);

// 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;
}
catch
{
// validation failed

return false;
}
}