CSharp - Validating an XML Document with Default Validation Event Handling

Introduction

In the following example, we construct our typical XML document.

Then validate it against an XML schema.

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. j a  v a2 s .co  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("MiddleInitial", "C"),
            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, null);
        Console.WriteLine("Document validated successfully.");
      }
      catch (XmlSchemaValidationException ex)
      {
        Console.WriteLine("Exception occurred: {0}", ex.Message);
        Console.WriteLine("Document validated unsuccessfully.");
      }

    }
}

Result

Related Topic