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

Description

Unsuccessfully Validating an XML Document Against an 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.  j a  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, (o, vea) =>
                 {
                   Console.WriteLine(
                     "A validation error occurred processing object type {0}.",
                     o.GetType().Name);
        
                   Console.WriteLine(vea.Message);
        
                   throw (new Exception(vea.Message));
            });
        
          Console.WriteLine("Document validated successfully.");
        }
        catch (Exception ex)
        {
          Console.WriteLine("Exception occurred: {0}", ex.Message);
          Console.WriteLine("Document validated unsuccessfully.");
        }
    
    }
}

Result

Related Topic