Validate an XML Document Against a Schema - CSharp XML

CSharp examples for XML:XML Document

Description

Validate an XML Document Against a Schema

Demo Code


using System;//from  w  w w.  ja  v a2  s. c om
using System.Xml;
using System.Xml.Schema;

public class ValidateXml
{
    [STAThread]
    private static void Main()
    {
        ConsoleValidator consoleValidator = new ConsoleValidator();
        Console.WriteLine("Validating ProductCatalog.xml.");

        bool success = consoleValidator.ValidateXml("ProductCatalog.xml", "ProductCatalog.xsd");
        if (!success)
        {
            Console.WriteLine("Validation failed.");
        }
        else
        {
            Console.WriteLine("Validation succeeded.");
        }

        Console.WriteLine("Validating ProductCatalog_Invalid.xml.");
        success = consoleValidator.ValidateXml("ProductCatalog_Invalid.xml", "ProductCatalog.xsd");
        if (!success)
        {
            Console.WriteLine("Validation failed.");
        }
        else
        {
            Console.WriteLine("Validation succeeded.");
        }
    }
}

public class ConsoleValidator
{
    private bool failed;

    public bool Failed
    {
        get { return failed; }
    }

    public bool ValidateXml(string xmlFilename, string schemaFilename)
    {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;

        XmlSchemaSet schemas = new XmlSchemaSet();
        settings.Schemas = schemas;
        schemas.Add(null, schemaFilename);

        settings.ValidationEventHandler += ValidationEventHandler;

        XmlReader validator = XmlReader.Create(xmlFilename, settings);

        failed = false;
        try
        {
            while (validator.Read())
            { }
        }
        catch (XmlException err)
        {
            Console.WriteLine("A critical XML error has occurred.");
            Console.WriteLine(err.Message);
            failed = true;
        }
        finally
        {
            validator.Close();
        }

        return !failed;
    }

    private void ValidationEventHandler(object sender, ValidationEventArgs args)
    {
        failed = true;

        Console.WriteLine("Validation error: " + args.Message);
    }

}

Result


Related Tutorials