The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Extensions.Validate Method (XDocument, XmlSchemaSet, ValidationEventHandler)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

This method validates that an XDocument conforms to an XSD in an XmlSchemaSet.

Namespace:   System.Xml.Schema
Assembly:  System.Xml.Linq (in System.Xml.Linq.dll)

public static void Validate(
	this XDocument source,
	XmlSchemaSet schemas,
	ValidationEventHandler validationEventHandler


Type: System.Xml.Linq.XDocument

The XDocument to validate.

Type: System.Xml.Schema.XmlSchemaSet

An XmlSchemaSet to validate against.

Type: System.Xml.Schema.ValidationEventHandler

A ValidationEventHandler for an event that occurs when the reader encounters validation errors. If null, throws an exception upon validation errors.

Exception Condition

Thrown for XML Schema Definition Language (XSD) validation errors.

This extension method validates that the XDocument conforms to the schema content model in XmlSchemaSet.

The following example creates an XmlSchemaSet, then validates two XDocument objects against the schema set. One of the documents is valid, the other is not.

                string xsdMarkup =
    @"<xsd:schema xmlns:xsd=''>
       <xsd:element name='Root'>
          <xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>
          <xsd:element name='Child2' minOccurs='1' maxOccurs='1'/>
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));

XDocument doc1 = new XDocument(
    new XElement("Root",
        new XElement("Child1", "content1"),
        new XElement("Child2", "content1")

XDocument doc2 = new XDocument(
    new XElement("Root",
        new XElement("Child1", "content1"),
        new XElement("Child3", "content1")

Console.WriteLine("Validating doc1");
bool errors = false;
doc1.Validate(schemas, (o, e) =>
                         Console.WriteLine("{0}", e.Message);
                         errors = true;
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");

Console.WriteLine("Validating doc2");
errors = false;
doc2.Validate(schemas, (o, e) =>
                         Console.WriteLine("{0}", e.Message);
                         errors = true;
Console.WriteLine("doc2 {0}", errors ? "did not validate" : "validated");

This example produces the following output:

Validating doc1
doc1 validated

Validating doc2
The element 'Root' has invalid child element 'Child3'. List of possible elements expected: 'Child2'.
doc2 did not validate

.NET Framework
Available since 3.5
Return to top