CSharp - Validating XML Document Against XSD Schema with Validation Event Handler

Description

Validating XML Document Against XSD Schema with Validation Event Handler

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;

class Program/*from  ww w  .j  a  va  2s  .c  o  m*/
{
    static void Main(string[] args)
    {
        XDocument xDocument = new XDocument(
      new XElement("Books",
              new XElement("Book",
                new XAttribute("type", "Author"),
                new XElement("FirstName", "Joe"),
                new XElement("LastName", "Ruby")),
              new XElement("Book",
                new XAttribute("type", "Editor"),
                new XElement("FirstName", "PHP"),
                new XElement("LastName", "Python"))));

        Console.WriteLine("Here is the source XML document:");
        Console.WriteLine("{0}{1}{1}", xDocument, System.Environment.NewLine);

        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.Add(null, "bookparticipants.xsd");

        try
        {
            xDocument.Validate(schemaSet, MyValidationEventHandler);
            Console.WriteLine("Document validated successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception occurred: {0}", ex.Message);
            Console.WriteLine("Document validated unsuccessfully.");
        }



    }
    static void MyValidationEventHandler(object o, ValidationEventArgs vea)
    {

        Console.WriteLine("A validation error occurred processing object type {0}.", o.GetType().Name);

        Console.WriteLine(vea.Message);
        throw (new Exception(vea.Message));
    }
}

Result

In the example, we create our typical XML document and display it to the console.

Next, we instantiate an XmlSchemaSet object and add the inferred schema file.

Then we call the Validate extension method on the XML document passing it the schema set and our validation event handling method.

Related Topic