.NET Brain Droppings

I'm a Microsoft Certified Architect (MCA)... Feel free to ask me about the program...

April 2004 - Posts

XmlValidatingReader Sample Code

I had to work up a sample of the XmlValidatingReader for a coworker, so I though I'd share it with everyone.  Here is a quick example of using the XmlValidatingReader.  There are other ways to construct/use it, but this is the most common method around here.  Hope this helps someone.

BTW: This is permanently archived at http://weblogs.asp.net/dbrowning/articles/114561.aspx

using System;

using System.IO;

using System.Xml;

using System.Xml.Schema;

 

 

namespace ConsoleApplication1

{

     

      class Class1

      {

           

            [STAThread]

            static void Main(string[] args)

            {

                  // path's to xml/xsd

                  const string path = @"C:\Projects\PSLL\ConsoleApplication1";

                  const string xmlPath = path + @"\franchise_detail.xml";

                  const string xsdPath = path + @"\Program.xsd";

 

                  // Create a new validating reader

                  XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(new StreamReader(xmlPath)));

                 

                  // Create a schema collection, add the xsd to it

                  XmlSchemaCollection schemaCollection = new XmlSchemaCollection();

                  schemaCollection.Add("http://detail.franchise.scarlett",xsdPath);

 

                  // Add the schema collection to the XmlValidatingReader

                  reader.Schemas.Add(schemaCollection);

 

                  Console.Write("Validating....");

 

                  // Wire up the call back.  The ValidationEvent is fired when the

                  // XmlValidatingReader hits an issue validating a section of the xml

                  reader.ValidationEventHandler += new ValidationEventHandler(reader_ValidationEventHandler);

                 

                  // Iterate through the xml document

                  while(reader.Read())

                  {

                        Console.Write(".");

                  }

 

                  Console.WriteLine("\n");

 

                  Console.ReadLine();

 

 

            }

 

            private static void reader_ValidationEventHandler(object sender, ValidationEventArgs e)

            {

                  // Report back error information to the console...

                  Console.WriteLine("Bad stuff happened");

                  Console.WriteLine(e.Exception.Message);

                  Console.WriteLine(e.Exception.LineNumber);

 

            }

      }

}

 

More Posts