Caveman's Blog

My commitment to learning.

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();
    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);

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);
         case XmlSeverityType.Warning:
             Console.WriteLine("Schema Validation Warning: {0}", e.Message);
    return 0;

Written by cavemansblog

July 6, 2012 at 11:17 am

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: