Sunday, June 03, 2007

.NET 2.0: Validate XML Using XSD Schema

Below class, written by myself, will validate a XML file based on its XSD file using .NET 2.0 technology. Please note .NET 1.1 is not compatible.

using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;
 
class XMLValidator
{
    static StringBuilder errBuilder;
 
    public static bool ValidateXML(string xmlFile, string xsdFile)
    {
        errBuilder = new StringBuilder();
 
        XmlSchemaSet xs = new XmlSchemaSet();
        xs.Add(null, xsdFile);
 
        XmlReader reader = null;
 
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationEventHandler += new ValidationEventHandler(BlogSettingsValidationEventHandler);
        settings.ValidationType = ValidationType.Schema;
        settings.Schemas = xs; 
 
        reader = XmlReader.Create(xmlFile, settings);
        while (reader.Read()) { }
  
        return (errBuilder.ToString() == String.Empty);
    }
 
    private static void BlogSettingsValidationEventHandler(object sender, ValidationEventArgs e)
    {
        if (e.Severity == XmlSeverityType.Warning  e.Severity == XmlSeverityType.Error)
        {
            errBuilder.Append("Error");
            //errBuilder.Append(e.Message);
        }
    }
}

To invoke the method, do something like below:

if (XMLValidator.ValidateXML(xmlFile, xsdFile))
{
    // Good
}
else
{
    // Bad
}

Have fun!

No comments:

Post a Comment

Do provide your constructive comment. I appreciate that.