CSharp - Unsuccessfully Validating XML Document Against XSD Schema Using a Lambda Expression

Description

Unsuccessfully Validating XML Document Against XSD Schema Using a Lambda Expression

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  2s.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("MiddleName", "Carson"),
      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");

      xDocument.Validate(schemaSet, (o, vea) =>
        {
          Console.WriteLine("An exception occurred processing object type {0}.",
            o.GetType().Name);

          Console.WriteLine("{0}{1}", vea.Message, System.Environment.NewLine);
        },
        true);

      foreach(XElement element in xDocument.Descendants())
      {
        Console.WriteLine("Element {0} is {1}", element.Name,
          element.GetSchemaInfo().Validity);

        XmlSchemaElement se = element.GetSchemaInfo().SchemaElement;
        if (se != null)
        {
          Console.WriteLine(
            "Schema element {0} must have MinOccurs = {1} and MaxOccurs = {2}{3}",
            se.Name, se.MinOccurs, se.MaxOccurs, System.Environment.NewLine);
        }
        else
        {
          //  Invalid elements will not have a SchemaElement.
          Console.WriteLine();
        }
      }
    }
}

Result

Related Topic