Επεξεργασία

Κοινή χρήση μέσω


Extensions.Validate Method

Definition

Validates that an XDocument, an XElement, or an XAttribute conforms to an XSD in an XmlSchemaSet.

Overloads

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

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

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

This method validates that an XAttribute conforms to a specified XmlSchemaObject and an XmlSchemaSet.

Validate(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).

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

This method validates that an XElement sub-tree conforms to a specified XmlSchemaObject and an XmlSchemaSet.

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)

Validates that an XAttribute conforms to a specified XmlSchemaObject and an XmlSchemaSet, optionally populating the XML tree with the post-schema-validation infoset (PSVI).

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)

Validates that an XElement sub-tree conforms to a specified XmlSchemaObject and an XmlSchemaSet, optionally populating the XML tree with the post-schema-validation infoset (PSVI).

Remarks

These methods use an underlying XmlReader to validate the XML tree against an XSD.

Validation error and warning messages are handled using the ValidationEventHandler delegate. If no event handler is provided to these methods, validation errors are exposed as an XmlSchemaValidationException. Validation warnings do not cause an XmlSchemaValidationException to be thrown.

Some of these extension methods optionally allow population of the post-schema-validation infoset (PSVI).

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

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

public:
[System::Runtime::CompilerServices::Extension]
 static void Validate(System::Xml::Linq::XDocument ^ source, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler);
public static void Validate (this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler);
public static void Validate (this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler);
static member Validate : System.Xml.Linq.XDocument * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler -> unit
<Extension()>
Public Sub Validate (source As XDocument, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler)

Parameters

source
XDocument

The XDocument to validate.

schemas
XmlSchemaSet

An XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

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

Exceptions

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

Examples

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='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: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", "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();  
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");  
                Dim errors As Boolean = False  

Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)  
    Console.WriteLine("{0}", e.Message)  
    errors = True  
End Sub  

Sub Main()  
    Dim xsdMarkup As XDocument = _  
    <?xml version='1.0'?>  
    <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:sequence>  
            </xsd:complexType>  
        </xsd:element>  
    </xsd:schema>  

    Dim schemas As XmlSchemaSet = New XmlSchemaSet()  
    schemas.Add("", xsdMarkup.CreateReader)  

    Dim doc1 As XDocument = _  
    <?xml version='1.0'?>  
    <Root>  
        <Child1>content1</Child1>  
        <Child2>content2</Child2>  
    </Root>  

    Dim doc2 As XDocument = _  
    <?xml version='1.0'?>  
    <Root>  
        <Child1>content1</Child1>  
        <Child3>content1</Child3>  
    </Root>  

    Console.WriteLine("Validating doc1")  
    errors = False  
    doc1.Validate(schemas, AddressOf XSDErrors)  
    Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))  

    Console.WriteLine()  
    Console.WriteLine("Validating doc2")  
    errors = False  
    doc2.Validate(schemas, AddressOf XSDErrors)  
    Console.WriteLine("doc2 {0}", IIf(errors, "did not validate", "validated"))  
End Sub  

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  

Remarks

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

Applies to

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

This method validates that an XAttribute conforms to a specified XmlSchemaObject and an XmlSchemaSet.

public:
[System::Runtime::CompilerServices::Extension]
 static void Validate(System::Xml::Linq::XAttribute ^ source, System::Xml::Schema::XmlSchemaObject ^ partialValidationType, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler);
public static void Validate (this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler);
public static void Validate (this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler);
static member Validate : System.Xml.Linq.XAttribute * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler -> unit
<Extension()>
Public Sub Validate (source As XAttribute, partialValidationType As XmlSchemaObject, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler)

Parameters

source
XAttribute

The XAttribute to validate.

partialValidationType
XmlSchemaObject

An XmlSchemaObject that specifies the sub-tree to validate.

schemas
XmlSchemaSet

An XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

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

Exceptions

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

Examples

                string xsdMarkup =  
    @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>  
       <xsd:element name='Root'>  
        <xsd:complexType>  
         <xsd:simpleContent>  
          <xsd:extension base='xsd:string'>  
           <xsd:attribute name='Lang' use='required'>  
            <xsd:simpleType>  
             <xsd:restriction base='xsd:token'>  
              <xsd:enumeration value='C#'/>  
              <xsd:enumeration value='VB'/>  
             </xsd:restriction>  
            </xsd:simpleType>  
           </xsd:attribute>  
          </xsd:extension>  
         </xsd:simpleContent>  
        </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 XAttribute("Lang", "C#")  
    )  
);  

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");  

Console.WriteLine();  
Console.WriteLine("Validating Lang attribute ...");  
XAttribute lang = doc1.Root.Attribute("Lang");  

errors = false;  
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    });  
Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");  

// the following makes the Lang attribute invalid according to the schema  
lang.Value = "VC";  

Console.WriteLine();  
Console.WriteLine("Validating Lang attribute ...");  

errors = false;  
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    });  
Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");  
                Dim errors As Boolean = False  

Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)  
    Console.WriteLine("{0}", e.Message)  
    errors = True  
End Sub  

Sub Main()  
    Dim xsdMarkup As XDocument = _  
      <?xml version='1.0'?>  
      <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>  
          <xsd:element name='Root'>  
              <xsd:complexType>  
                  <xsd:simpleContent>  
                      <xsd:extension base='xsd:string'>  
                          <xsd:attribute name='Lang' use='required'>  
                              <xsd:simpleType>  
                                  <xsd:restriction base='xsd:token'>  
                                      <xsd:enumeration value='C#'/>  
                                      <xsd:enumeration value='VB'/>  
                                  </xsd:restriction>  
                              </xsd:simpleType>  
                          </xsd:attribute>  
                      </xsd:extension>  
                  </xsd:simpleContent>  
              </xsd:complexType>  
          </xsd:element>  
      </xsd:schema>  

    Dim schemas As XmlSchemaSet = New XmlSchemaSet()  
    schemas.Add("", xsdMarkup.CreateReader)  

    Dim doc1 As XDocument = <?xml version='1.0'?>  
                            <Root Lang='C#'/>  

    Console.WriteLine("Validating doc1 ...")  
    errors = False  
    doc1.Validate(schemas, AddressOf XSDErrors, True)  
    Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))  

    Console.WriteLine()  
    Console.WriteLine("Validating Lang attribute ...")  
    Dim lang As XAttribute = doc1.Root.Attribute("Lang")  

    errors = False  
    lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, AddressOf XSDErrors)  
    Console.WriteLine("lang {0}", IIf(errors, "did not validate", "validated"))  

    ' the following makes the Lang attribute invalid according to the schema  
    lang.Value = "VC"  

    Console.WriteLine()  
    Console.WriteLine("Validating Lang attribute ...")  

    errors = False  
    lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, AddressOf XSDErrors)  
    Console.WriteLine("lang {0}", IIf(errors, "did not validate", "validated"))  
End Sub  

This example produces the following output:

Validating doc1 ...  
doc1 validated  

Validating Lang attribute ...  
lang validated  

Validating Lang attribute ...  
The 'Lang' attribute is invalid - The value 'VC' is invalid according to its datatype 'Token' - The Enumeration constraint failed.  
lang did not validate  

Remarks

You can use this method to validate that an XAttribute conforms to a schema. You typically use this method when you have modified an attribute, and you want to make sure that it still conforms to its schema. You could validate the entire document, but it takes less processing time to validate just the attribute.

If you pass null for validationEventHandler, this method raises an exception upon validation errors. Validation warnings will not raise an exception.

To validate an attribute, you use an instance of XmlSchemaObject. You can obtain this instance in various ways. An easy way is as follows:

  1. Validate that a document conforms to a schema.

  2. Add the post-schema-validation infoset (PSVI) by calling the Validate extension method.

  3. Call the GetSchemaInfo extension method to retrieve an object that implements IXmlSchemaInfo. From the retrieved object, you can get an XmlSchemaObject.

After you have an instance of an XmlSchemaObject, you can use this method to validate an attribute.

Applies to

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

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

public:
[System::Runtime::CompilerServices::Extension]
 static void Validate(System::Xml::Linq::XDocument ^ source, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler, bool addSchemaInfo);
public static void Validate (this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler, bool addSchemaInfo);
public static void Validate (this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo);
static member Validate : System.Xml.Linq.XDocument * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler * bool -> unit
<Extension()>
Public Sub Validate (source As XDocument, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler, addSchemaInfo As Boolean)

Parameters

source
XDocument

The XDocument to validate.

schemas
XmlSchemaSet

An XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

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

addSchemaInfo
Boolean

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

Exceptions

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

Examples

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);  
                Dim errors As Boolean = False  

Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)  
    Console.WriteLine("{0}", e.Message)  
    errors = True  
End Sub  

Sub Main()  
    Dim xsdMarkup As XDocument = _  
    <?xml version='1.0'?>  
    <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>  
    Dim schemas As XmlSchemaSet = New XmlSchemaSet()  
    schemas.Add("", xsdMarkup.CreateReader)  

    Dim doc1 As XDocument = <?xml version='1.0'?>  
                            <Root>  
                                <Child1>c1</Child1>  
                                <Child2>c2</Child2>  
                            </Root>  
    Dim doc2 As XDocument = <?xml version='1.0'?>  
                            <Root>  
                                <Child1>content1</Child1>  
                                <Child3>content1</Child3>  
                            </Root>  

    Console.WriteLine("Validating doc1")  
    errors = False  
    doc1.Validate(schemas, AddressOf XSDErrors, True)  
    Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))  

    Console.WriteLine()  
    Console.WriteLine("Validating doc2")  
    errors = False  
    doc2.Validate(schemas, AddressOf XSDErrors, True)  
    Console.WriteLine("doc2 {0}", IIf(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)  
End Sub  

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);  
}  
                Private Sub DumpInvalidNodes(ByVal el As XElement)  
    If el.GetSchemaInfo.Validity <> XmlSchemaValidity.Valid Then  
        Console.WriteLine("Invalid Element {0}", _  
            el _  
            .AncestorsAndSelf _  
            .InDocumentOrder() _  
            .Aggregate("", _  
                Function(ByVal s, ByVal i) s + "/" + i.Name.ToString()))  
    End If  
    For Each att As XAttribute In el.Attributes()  
        If att.GetSchemaInfo.Validity <> XmlSchemaValidity.Valid Then  
            Console.WriteLine("Invalid Attribute {0}", _  
                att _  
                .Parent _  
                .AncestorsAndSelf() _  
                .InDocumentOrder() _  
                .Aggregate("", _  
                    Function(ByVal s, ByVal i) s + "/" + i.Name.ToString()) + _  
                    "/@" + att.Name.ToString())  
        End If  
    Next  
    For Each child As XElement In el.Elements()  
        DumpInvalidNodes(child)  
    Next  
End Sub  

Dim errors As Boolean = False  

Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)  
    Console.WriteLine("{0}", e.Message)  
    errors = True  
End Sub  

Sub Main()  
    Dim xsdMarkup As XDocument = _  
        <?xml version='1.0'?>  
        <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>  

    Dim schemas As XmlSchemaSet = New XmlSchemaSet()  
    schemas.Add("", xsdMarkup.CreateReader)  

    Dim doc1 As XDocument = _  
        <?xml version='1.0'?>  
        <Root>  
            <Child1>  
                <GrandChild1>AAA</GrandChild1>  
                <GrandChild2>ZZZ</GrandChild2>  
                <GrandChild3>ZZZ</GrandChild3>  
            </Child1>  
        </Root>  

    Console.WriteLine("Validating doc1 ...")  
    errors = False  
    doc1.Validate(schemas, AddressOf XSDErrors, True)  
    Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))  
    DumpInvalidNodes(doc1.Root)  
End Sub  

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  

Remarks

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.

Applies to

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

This method validates that an XElement sub-tree conforms to a specified XmlSchemaObject and an XmlSchemaSet.

public:
[System::Runtime::CompilerServices::Extension]
 static void Validate(System::Xml::Linq::XElement ^ source, System::Xml::Schema::XmlSchemaObject ^ partialValidationType, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler);
public static void Validate (this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler);
public static void Validate (this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler);
static member Validate : System.Xml.Linq.XElement * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler -> unit
<Extension()>
Public Sub Validate (source As XElement, partialValidationType As XmlSchemaObject, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler)

Parameters

source
XElement

The XElement to validate.

partialValidationType
XmlSchemaObject

An XmlSchemaObject that specifies the sub-tree to validate.

schemas
XmlSchemaSet

An XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

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

Exceptions

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

Examples

                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:complexType>  
            <xsd:sequence>  
             <xsd:element name='GrandChild1' minOccurs='1' maxOccurs='1'/>  
             <xsd:element name='GrandChild2' minOccurs='1' maxOccurs='2'/>  
            </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", "gc"),  
            new XElement("GrandChild2", "gc")  
        )  
    )  
);  

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");  

Console.WriteLine();  
Console.WriteLine("Validating Child1 after first edit ...");  
XElement child1 = doc1.Element("Root").Element("Child1");  
child1.Add(new XElement("GrandChild2", "gc"));  
errors = false;  
child1.Validate(child1.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    });  
Console.WriteLine("child1 {0}", errors ? "did not validate" : "validated");  

// the following makes the Child1 element invalid according to the schema  
child1.Add(new XElement("GrandChild3", "gc"));  
Console.WriteLine();  
Console.WriteLine("Validating Child1 after second edit ...");  
child1.Validate(child1.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    });  
Console.WriteLine("child1 {0}", errors ? "did not validate" : "validated");  
                Dim errors As Boolean = False  

Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)  
    Console.WriteLine("{0}", e.Message)  
    errors = True  
End Sub  

Sub Main()  

    Dim xsdMarkup As XDocument = _  
        <?xml version='1.0'?>  
        <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:complexType>  
                                <xsd:sequence>  
                                    <xsd:element name='GrandChild1' minOccurs='1' maxOccurs='1'/>  
                                    <xsd:element name='GrandChild2' minOccurs='1' maxOccurs='2'/>  
                                </xsd:sequence>  
                            </xsd:complexType>  
                        </xsd:element>  
                    </xsd:sequence>  
                </xsd:complexType>  
            </xsd:element>  
        </xsd:schema>  

    Dim schemas As XmlSchemaSet = New XmlSchemaSet()  
    schemas.Add("", xsdMarkup.CreateReader)  

    Dim doc1 As XDocument = _  
        <?xml version='1.0'?>  
        <Root>  
            <Child1>  
                <GrandChild1>gc</GrandChild1>  
                <GrandChild2>gc</GrandChild2>  
            </Child1>  
        </Root>  

    Console.WriteLine("Validating doc1 ...")  
    errors = False  
    doc1.Validate(schemas, AddressOf XSDErrors, True)  
    Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))  

    Console.WriteLine()  
    Console.WriteLine("Validating Child1 after first edit ...")  
    Dim child1 As XElement = doc1.Element("Root").Element("Child1")  
    child1.Add(<GrandChild2>gc</GrandChild2>)  
    errors = False  
    child1.Validate(child1.GetSchemaInfo().SchemaElement, schemas, AddressOf XSDErrors)  
    Console.WriteLine("child1 {0}", IIf(errors, "did not validate", "validated"))  

    ' the following makes the Child1 element invalid according to the schema  
    child1.Add(<GrandChild3>gc</GrandChild3>)  
    Console.WriteLine()  
    Console.WriteLine("Validating Child1 after second edit ...")  
    child1.Validate(child1.GetSchemaInfo().SchemaElement, schemas, AddressOf XSDErrors)  
    Console.WriteLine("child1 {0}", IIf(errors, "did not validate", "validated"))  
End Sub  

This example produces the following output:

Validating doc1 ...  
doc1 validated  

Validating Child1 after first edit ...  
child1 validated  

Validating Child1 after second edit ...  
The element 'Child1' has invalid child element 'GrandChild3'.  
child1 did not validate  

Remarks

You can use this method to validate that a sub-tree (with an XElement at its root) conforms to a schema. You typically use this method when you have modified a sub-tree, and you want to make sure that it still conforms to its schema. You could validate the entire document, but it takes less processing time to validate a just a sub-tree.

If you pass null for validationEventHandler, then this method raises an exception upon validation errors. Validation warnings will not raise an exception.

To validate a sub-tree, you use an instance of XmlSchemaObject. You can obtain this instance in various ways. An easy way is as follows:

  1. Validate that a document conforms to a schema.

  2. Add the post-schema-validation infoset (PSVI) by calling the Validate extension method.

  3. Call the GetSchemaInfo extension method to retrieve an object that implements IXmlSchemaInfo. From the retrieved object, you can get an XmlSchemaObject.

After you have an instance of an XmlSchemaObject, you can use this method to validate an sub-tree.

Applies to

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

Validates that an XAttribute conforms to a specified XmlSchemaObject and an XmlSchemaSet, optionally populating the XML tree with the post-schema-validation infoset (PSVI).

public:
[System::Runtime::CompilerServices::Extension]
 static void Validate(System::Xml::Linq::XAttribute ^ source, System::Xml::Schema::XmlSchemaObject ^ partialValidationType, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler, bool addSchemaInfo);
public static void Validate (this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler, bool addSchemaInfo);
public static void Validate (this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo);
static member Validate : System.Xml.Linq.XAttribute * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler * bool -> unit
<Extension()>
Public Sub Validate (source As XAttribute, partialValidationType As XmlSchemaObject, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler, addSchemaInfo As Boolean)

Parameters

source
XAttribute

The XAttribute to validate.

partialValidationType
XmlSchemaObject

An XmlSchemaObject that specifies the sub-tree to validate.

schemas
XmlSchemaSet

An XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

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

addSchemaInfo
Boolean

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

Exceptions

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

Examples

                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:element name='Root'>  
        <xsd:complexType>  
         <xsd:simpleContent>  
          <xsd:extension base='xsd:string'>  
           <xsd:attribute name='Lang' use='required'>  
            <xsd:simpleType>  
             <xsd:restriction base='xsd:token'>  
              <xsd:enumeration value='C#'/>  
              <xsd:enumeration value='VB'/>  
             </xsd:restriction>  
            </xsd:simpleType>  
           </xsd:attribute>  
          </xsd:extension>  
         </xsd:simpleContent>  
        </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 XAttribute("Lang", "C#")  
        )  
    );  

    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);  

    Console.WriteLine();  
    Console.WriteLine("Validating Lang attribute ...");  
    XAttribute lang = doc1.Element("Root").Attribute("Lang");  

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

    // the following makes the Lang attribute invalid according to the schema  
    lang.Value = "VC";  

    Console.WriteLine();  
    Console.WriteLine("Validating Lang attribute ...");  

    errors = false;  
    lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    }, true);  
    Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");  
    DumpInvalidNodes(doc1.Root);  
}  
                Private Sub DumpInvalidNodes(ByVal el As XElement)  
    If el.GetSchemaInfo.Validity <> XmlSchemaValidity.Valid Then  
        Console.WriteLine("Invalid Element {0}", _  
            el _  
            .AncestorsAndSelf _  
            .InDocumentOrder() _  
            .Aggregate("", _  
                Function(ByVal s, ByVal i) s + "/" + i.Name.ToString()))  
    End If  
    For Each att As XAttribute In el.Attributes()  
        If att.GetSchemaInfo.Validity <> XmlSchemaValidity.Valid Then  
            Console.WriteLine("Invalid Attribute {0}", _  
                att _  
                .Parent _  
                .AncestorsAndSelf() _  
                .InDocumentOrder() _  
                .Aggregate("", _  
                    Function(ByVal s, ByVal i) s + "/" + i.Name.ToString()) + _  
                    "/@" + att.Name.ToString())  
        End If  
    Next  
    For Each child As XElement In el.Elements()  
        DumpInvalidNodes(child)  
    Next  
End Sub  

Dim errors As Boolean = False  

Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)  
    Console.WriteLine("{0}", e.Message)  
    errors = True  
End Sub  

Sub Main()  

    Dim xsdMarkup As XDocument = _  
        <?xml version='1.0'?>  
        <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>  
            <xsd:element name='Root'>  
                <xsd:complexType>  
                    <xsd:simpleContent>  
                        <xsd:extension base='xsd:string'>  
                            <xsd:attribute name='Lang' use='required'>  
                                <xsd:simpleType>  
                                    <xsd:restriction base='xsd:token'>  
                                        <xsd:enumeration value='C#'/>  
                                        <xsd:enumeration value='VB'/>  
                                    </xsd:restriction>  
                                </xsd:simpleType>  
                            </xsd:attribute>  
                        </xsd:extension>  
                    </xsd:simpleContent>  
                </xsd:complexType>  
            </xsd:element>  
        </xsd:schema>  

    Dim schemas As XmlSchemaSet = New XmlSchemaSet()  
    schemas.Add("", xsdMarkup.CreateReader)  

    Dim doc1 As XDocument = <?xml version='1.0'?>  
                            <Root Lang='C#'/>  

    Console.WriteLine("Validating doc1 ...")  
    errors = False  
    doc1.Validate(schemas, AddressOf XSDErrors, True)  
    Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))  
    DumpInvalidNodes(doc1.Root)  

    Console.WriteLine()  
    Console.WriteLine("Validating Lang attribute ...")  
    Dim lang As XAttribute = doc1.Element("Root").Attribute("Lang")  

    errors = False  
    lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, AddressOf XSDErrors, True)  
    Console.WriteLine("lang {0}", IIf(errors, "did not validate", "validated"))  
    DumpInvalidNodes(doc1.Root)  

    ' the following makes the Lang attribute invalid according to the schema  
    lang.Value = "VC"  

    Console.WriteLine()  
    Console.WriteLine("Validating Lang attribute ...")  

    errors = False  
    lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, AddressOf XSDErrors, True)  
    Console.WriteLine("lang {0}", IIf(errors, "did not validate", "validated"))  
    DumpInvalidNodes(doc1.Root)  
End Sub  

This example produces the following output:

Validating doc1 ...  
doc1 validated  

Validating Lang attribute ...  
lang validated  

Validating Lang attribute ...  
The 'Lang' attribute is invalid - The value 'VC' is invalid according to its datatype 'Token' - The Enumeration constraint failed.  
lang did not validate  
Invalid Attribute /Root/@Lang  

Remarks

You can use this method to validate that an XAttribute conforms to a schema. You typically use this method when you have modified an attribute, and you want to make sure that it still conforms to its schema. You could validate the entire document, but it takes less processing time to validate just the attribute.

If addSchemaInfo is true, this method populates the attribute with the post-schema-validation infoset (PSVI). After you have populated the XML tree with the PSVI, you can call Extensions.GetSchemaInfo on the validated attribute. This is useful if you are writing code that relies on data returned by GetSchemaInfo.

If you pass null for validationEventHandler, then this method raises an exception upon validation errors. Validation warnings will not raise an exception.

To validate an attribute, you use an instance of XmlSchemaObject. You can obtain this instance in various ways. An easy way is as follows:

  1. Validate that a document conforms to a schema.

  2. Add the post-schema-validation infoset (PSVI) by calling the Validate extension method.

  3. Call the GetSchemaInfo extension method to retrieve an object that implements IXmlSchemaInfo. From the retrieved object, you can get an XmlSchemaObject.

After you have an instance of an XmlSchemaObject, you can use this method to validate an attribute.

Applies to

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

Validates that an XElement sub-tree conforms to a specified XmlSchemaObject and an XmlSchemaSet, optionally populating the XML tree with the post-schema-validation infoset (PSVI).

public:
[System::Runtime::CompilerServices::Extension]
 static void Validate(System::Xml::Linq::XElement ^ source, System::Xml::Schema::XmlSchemaObject ^ partialValidationType, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler, bool addSchemaInfo);
public static void Validate (this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler, bool addSchemaInfo);
public static void Validate (this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo);
static member Validate : System.Xml.Linq.XElement * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler * bool -> unit
<Extension()>
Public Sub Validate (source As XElement, partialValidationType As XmlSchemaObject, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler, addSchemaInfo As Boolean)

Parameters

source
XElement

The XElement to validate.

partialValidationType
XmlSchemaObject

An XmlSchemaObject that specifies the sub-tree to validate.

schemas
XmlSchemaSet

An XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

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

addSchemaInfo
Boolean

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

Exceptions

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

Examples

                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);  
                Dim errors As Boolean = False  

Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)  
    Console.WriteLine("{0}", e.Message)  
    errors = True  
End Sub  

Sub Main()  
    Dim xsdMarkup As XDocument = _  
        <?xml version='1.0'?>  
        <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>  
    Dim schemas As XmlSchemaSet = New XmlSchemaSet()  
    schemas.Add("", xsdMarkup.CreateReader)  

    Dim doc1 As XDocument = _  
        <?xml version='1.0'?>  
        <Root>  
            <Child1>c1</Child1>  
            <Child2>c2</Child2>  
        </Root>  

    Dim doc2 As XDocument = _  
        <?xml version='1.0'?>  
        <Root>  
            <Child1>content1</Child1>  
            <Child3>content1</Child3>  
        </Root>  

    Console.WriteLine("Validating doc1")  
    errors = False  
    doc1.Validate(schemas, AddressOf XSDErrors, True)  
    Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))  

    Console.WriteLine()  
    Console.WriteLine("Validating doc2")  
    errors = False  
    doc2.Validate(schemas, AddressOf XSDErrors, True)  
    Console.WriteLine("doc2 {0}", IIf(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)  
End Sub  

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>  

Remarks

You can use this method to validate that a sub-tree (with an XElement at the root of the sub-tree) conforms to a schema. You typically use this method when you have modified a sub-tree, and you want to make sure that it still conforms to its schema. You could validate the entire document, but it takes less processing time to validate a just a sub-tree.

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

There are two aspects of populating the XML tree with the PSVI.

First, an annotation is added to all nodes in the tree such that you can now call GetSchemaInfo on an element or attribute in the tree.

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.

If you pass null for validationEventHandler, then this method raises an exception upon validation errors. Validation warnings will not raise an exception.

To validate a sub-tree, you use an instance of XmlSchemaObject. You can obtain this instance in various ways. An easy way is as follows:

  1. Validate that a document conforms to a schema.

  2. Add the post-schema-validation infoset (PSVI) by calling the Validate extension method.

  3. Call the GetSchemaInfo extension method to retrieve an object that implements IXmlSchemaInfo. From the retrieved object, you can get an XmlSchemaObject.

After you have an instance of an XmlSchemaObject, you can use this method to validate a sub-tree..

Applies to