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

Description

Unsuccessfully Validating an XML Document Against an 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  w w  w  .  ja  va  2  s. c  om
{
    static void Main(string[] args)
    {
        XDocument xDocument = new XDocument(
      new XElement("Books",
        new XElement("Book",
          new XAttribute("type", "Author"),
          new XAttribute("language", "English"),
          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

Related Topic