Use XmlReaderSettings to validate the Xml document : Schema : XML C# Source Code


Custom Search

C# Source Code » XML » Schema »

 

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) {
            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);
    }
}

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

           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo XML
» Schema