Validate an XML Document Against a Schema : Schema : XML C# Source Code


Custom Search

C# Source Code » XML » Schema »

 

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

           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo XML
» Schema