Use XmlReaderSettings to validate the Xml document : Schema « XML « C# / C Sharp

Use XmlReaderSettings to validate the Xml document


using System;
using System.Xml;
using System.Xml.Schema;

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) {
            failed = true;
        } finally {
        return !failed;
    private void ValidationEventHandler(object sender, ValidationEventArgs args) {
        failed = true;
        Console.WriteLine("Validation error: " + args.Message);

class MainClass {
    private static void Main() {
        ConsoleValidator consoleValidator = new ConsoleValidator();
        bool success = consoleValidator.ValidateXml("ProductCatalog.xml", "ProductCatalog.xsd");


Related examples in the same category

1.Set XmlReaderSettings
2.Choose ValidationType
3.Validate an XML Document Against a Schema
4.Validate Schema
5.Use XML schema to validate XML documents
6.Strip Non Valid XML Characters.
7.Is Well Formed Xml
8.XmlSchema is an in-memory representation of an XML Schema
9.Is Xml Valid
10.Xml Validation Helper
11.Get Intrinsic Simple Types Names from System.Xml.Schema.DatatypeImplementation
12.Reads a XML schema file and returns the information found in that.
13.XML reading functionality