The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  75 Posts :: 0 Stories :: 49 Comments :: 2 Trackbacks

Ads

Archives

Post Categories

Open Source Projects

Other Blogs

This is a utility class (with a static ValidateXml method) that will allow you to quickly validate an XML file against its XSD. The code makes use of the XmlReaderSettings class as well as an XmlReader class. The crunch work is done in the ValidateXml method. The XmlReaderSettings class takes a callback delegate that is called only when an error in validation occurs.
 
Here is the full code listing for the class.
  

using System;

using System.Xml;

using System.Xml.Schema;

 

namespace Utilities

{

    public static class XMLUtilities

    {

        private static bool _validateSuccess = true;

        private static bool ValidateXml(String fileName)

        {

            _validateSuccess = true;    //Reset the "Success" variable - it will be set to false in the callback method if and error occurs

 

            XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();

            xmlReaderSettings.ValidationType = ValidationType.Schema;

            xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

            XmlReader xmlReader = XmlReader.Create(fileName, xmlReaderSettings);

 

            // Read XML data. If _validateSuccess has been st to false, no need to continue reading

            while (xmlReader.Read() && _validateSuccess)

            {

            }

            xmlReader.Close();

 

            return _validateSuccess;

        }

 

        private static void ValidationCallBack(Object sender, ValidationEventArgs args)

        {

            _validateSuccess = false;

        }

    }

}

posted on Wednesday, October 24, 2007 8:19 AM
Comments have been closed on this topic.