Validate an XML Document Against a Schema : Schema « XML « C# / C Sharp






Validate an XML Document Against a Schema

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

public class ConsoleValidator {
    public static void ValidateXml(string xmlFilename, string schemaFilename) {
        XmlTextReader r = new XmlTextReader(xmlFilename);
        XmlValidatingReader validator = new XmlValidatingReader(r);
        validator.ValidationType = ValidationType.Schema;

        XmlSchemaCollection schemas = new XmlSchemaCollection();
        schemas.Add(null, schemaFilename);
        validator.Schemas.Add(schemas);

        validator.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
            
        try {
            while (validator.Read())
            {}
        }catch (XmlException err) {
            Console.WriteLine(err.Message);
        }finally {
            validator.Close();
        }
    }

    private static void ValidationEventHandler(object sender, ValidationEventArgs args) {
        Console.WriteLine("Validation error: " + args.Message);
    }
    private static void Main() {
        Console.WriteLine("Validating your.xml.");
        ValidateXml("your.xml", "your.xsd");
    }    
}

           
         
    
    
  








Related examples in the same category

1.Set XmlReaderSettings
2.Choose ValidationType
3.Validate Schema
4.Use XML schema to validate XML documents
5.Use XmlReaderSettings to validate the Xml document
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