Extensions.Validate Method (XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

Validates that an XDocument conforms to an XSD in an XmlSchemaSet, optionally populating the XML tree with the post-schema-validation infoset (PSVI).

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

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

Parameters

source
Type: System.Xml.Linq.XDocument

The XDocument to validate.

schemas
Type: System.Xml.Schema.XmlSchemaSet

An XmlSchemaSet to validate against.

validationEventHandler
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.

addSchemaInfo
Type: System.Boolean

A Boolean indicating whether to populate the post-schema-validation infoset (PSVI).

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type XDocument. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).

ExceptionCondition
XmlSchemaValidationException

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

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

If addSchemaInfo is true, this method populates the XML tree with the post-schema-validation infoset (PSVI).

There are two steps to populating the XML tree with the PSVI.

  1. First, an annotation is added to all nodes in the tree to enable you to call Extensions.GetSchemaInfo or Extensions.GetSchemaInfo on an element or attribute in the tree.

  2. Second, default elements and attributes defined in the XSD are added to the XML tree. By calling one of the GetSchemaInfo methods, you can determine if a specific element or attribute was added from the XSD as a default element or attribute.

The following example contains an XSD that defines the Child2 element with an Att1 attribute with a default value. After successfully validating the document, the attribute with the default value is added to the XML tree. Note that the default attribute is not added to doc2, which does not validate against the schema.

string xsdMarkup =
    @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
       <xsd:element name='Root'>
        <xsd:complexType>
         <xsd:sequence>
          <xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>
          <xsd:element name='Child2' minOccurs='1' maxOccurs='1'>
           <xsd:complexType>
            <xsd:simpleContent>
             <xsd:extension base='xsd:string'>
              <xsd:attribute name='Att1' default='Att1 Default Value'/>
             </xsd:extension>
            </xsd:simpleContent>
           </xsd:complexType>
          </xsd:element>
         </xsd:sequence>
        </xsd:complexType>
       </xsd:element>
      </xsd:schema>";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));

XDocument doc1 = new XDocument(
    new XElement("Root",
        new XElement("Child1", "c1"),
        new XElement("Child2", "c2")
    )
);

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;
                           }, true);
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");

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

Console.WriteLine();
Console.WriteLine("Contents of doc1:");
Console.WriteLine(doc1);

Console.WriteLine();
Console.WriteLine("Contents of doc2:");
Console.WriteLine(doc2);

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

Contents of doc1:
<Root>
  <Child1>c1</Child1>
  <Child2 Att1="Att1 Default Value">c2</Child2>
</Root>

Contents of doc2:
<Root>
  <Child1>content1</Child1>
  <Child3>content1</Child3>
</Root>

The following example populates the tree with PSVI. After validation, it prints all elements and attributes in the tree that are invalid according to the PSVI.

static void DumpInvalidNodes(XElement el)
{
    if (el.GetSchemaInfo().Validity != XmlSchemaValidity.Valid)
        Console.WriteLine("Invalid Element {0}",
            el.AncestorsAndSelf()
            .InDocumentOrder()
            .Aggregate("", (s, i) => s + "/" + i.Name.ToString()));
    foreach (XAttribute att in el.Attributes())
        if (att.GetSchemaInfo().Validity != XmlSchemaValidity.Valid)
            Console.WriteLine("Invalid Attribute {0}",
                att
                .Parent
                .AncestorsAndSelf()
                .InDocumentOrder()
                .Aggregate("",
                    (s, i) => s + "/" + i.Name.ToString()) + "/@" + att.Name.ToString()
                );
    foreach (XElement child in el.Elements())
        DumpInvalidNodes(child);
}

static void Main(string[] args)
{
   string xsdMarkup =
        @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
           <xsd:simpleType name='GCType'>
            <xsd:restriction base='xsd:token'>
             <xsd:enumeration value='AAA'/>
             <xsd:enumeration value='BBB'/>
            </xsd:restriction>
           </xsd:simpleType>
           <xsd:element name='Root'>
            <xsd:complexType>
             <xsd:sequence>
              <xsd:element name='Child1' minOccurs='1' maxOccurs='1'>
               <xsd:complexType>
                <xsd:sequence>
                 <xsd:element name='GrandChild1' type='GCType'/>
                 <xsd:element name='GrandChild2' type='GCType'/>
                 <xsd:element name='GrandChild3' type='GCType'/>
                </xsd:sequence>
               </xsd:complexType>
              </xsd:element>
             </xsd:sequence>
            </xsd:complexType>
           </xsd:element>
          </xsd:schema>";
    
    XmlSchemaSet schemas = new XmlSchemaSet();
    schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));

    XDocument doc1 = new XDocument(
        new XElement("Root",
            new XElement("Child1",
                new XElement("GrandChild1", "AAA"),
                new XElement("GrandChild2", "ZZZ"),
                new XElement("GrandChild3", "ZZZ")
            )
        )
    );

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

This example produces the following output:

Validating doc1 ...
The 'GrandChild2' element is invalid - The value 'ZZZ' is invalid according to its datatype 'GCType' - The Enumeration constraint failed.
The 'GrandChild3' element is invalid - The value 'ZZZ' is invalid according to its datatype 'GCType' - The Enumeration constraint failed.
doc1 did not validate
Invalid Element /Root
Invalid Element /Root/Child1
Invalid Element /Root/Child1/GrandChild2
Invalid Element /Root/Child1/GrandChild3

.NET Framework

Supported in: 4.5, 4, 3.5

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft