"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

April 07, 2012

Tool Developer Notes - Part VII

[Previous post in series - Tool Developer Notes - Part VI]

Series of posts on learning's from developing tools using .NET platform. This post is about XML validation. Validating xml is based on defined format. Detecting in case there is a missing node / format issues. Define a schema for the xml format and validate it against the xml data

Step 1 - Define xml data format. Sample format provided below

Step 2 - Generate schema from the xml


Step 3 - .NET code snippet to validate the input xml format. stackoverflow approach is reused, Read schema from XSD filepath and input filepath is modified for this example. Sample Console Application

using System;
using System.Windows.Forms;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Xml;
using System.Xml.Schema;
using System.IO;
namespace TestExample
{
    class Program
    {
        public static void Main(string[] args)
        {
            ValidateXSD();
        }
        public static void ValidateXSD()
        {
            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(null, @"C:\Users\Desktop\XSD Post\Input.xsd");
                settings.ValidationType = ValidationType.Schema;
                settings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ValidationCallBack);
                var reader = XmlReader.Create(@"C:\Users\Desktop\XSD Post\Input.xml", settings);
                // Parse the file. 
                while (reader.Read());
            }
            catch (Exception EX)
            {
                MessageBox.Show(EX.Message);
            }
        }

       // Display any warnings or errors.
        private static void ValidationCallBack(object sender, ValidationEventArgs args)
        {
            if (args.Severity == XmlSeverityType.Warning)
                MessageBox.Show("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
            else
                MessageBox.Show("\tValidation error: " + args.Message);
        }
    }
}

Step 4 - In case of errors the actuall error would be caught in exception block

More Reads

Quick Aside on XML - The Wrong Way to Use XML


Happy Learning!!!

No comments: