Caveman's Blog

My commitment to learning.

Archive for the ‘Sample Code’ Category

Sample Code: Xml validation using XSD

leave a comment »


In this blog I will post a handy code snippet, that validates an XML file using an XSD file.

Import the following namespaces

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;

Validate a XML File

public static void ValidateXmlFile(string XMLfilename, string XSDfilename)
{
    //make sure the file exists
    if (!File.Exists(XMLfilename))
    {
        Console.WriteLine("Error: XML Data File '{0}' not found.", XMLfilename);
        return 0;
    }

    //Standard schema validation first
    XmlDocument document = new XmlDocument();
    try
    {
        document.Load(XMLfilename);
    }
    catch (XmlException xmle)
    {
        Console.WriteLine("!!!Error!!!\r\nXML Validation Failure: {0}\r\n\r\n", xmle.Message);
        return 0;
    }
    document.Schemas.Add(XSDfilename, "");
    ValidationEventHandler validation = new ValidationEventHandler(SchemaValidationHandler);
    document.Validate(validation);
}

Define a Schema Validation Handler

private static void SchemaValidationHandler(object sender, ValidationEventArgs e)
{
     switch (e.Severity)
     {
         case XmlSeverityType.Error:
             Console.WriteLine("Schema Validation Error: {0}", e.Message);
         break;
         case XmlSeverityType.Warning:
             Console.WriteLine("Schema Validation Warning: {0}", e.Message);
         break;
     }
    return 0;
}
Advertisements

Written by cavemansblog

July 6, 2012 at 11:17 am