Extensions.Validate 方法

定义

验证 XDocumentXElementXAttribute 是否与 XmlSchemaSet 中的 XSD 相符。Validates that an XDocument, an XElement, or an XAttribute conforms to an XSD in an XmlSchemaSet.

重载

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

此方法验证 XDocument 是否与 XmlSchemaSet 中的 XSD 相符。This method validates that an XDocument conforms to an XSD in an XmlSchemaSet.

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

此方法验证 XAttribute 是否与指定的 XmlSchemaObjectXmlSchemaSet 相符。This method validates that an XAttribute conforms to a specified XmlSchemaObject and an XmlSchemaSet.

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

验证 XDocument 是否与 XmlSchemaSet 中的某个 XSD 相符,并且可以选择使用架构验证后信息集 (PSVI) 填充 XML 树。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)

此方法验证 XElement 子树是否与指定的 XmlSchemaObjectXmlSchemaSet 相符。This method validates that an XElement sub-tree conforms to a specified XmlSchemaObject and an XmlSchemaSet.

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

验证 XAttribute 是否与指定的 XmlSchemaObjectXmlSchemaSet 相符,并且可以选择使用架构验证后信息集 (PSVI) 填充 XML 树。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)

验证 XElement 子树是否与指定的 XmlSchemaObjectXmlSchemaSet 相符,并且可以选择使用架构验证后信息集 (PSVI) 填充 XML 树。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).

注解

这些方法使用基础 XmlReader 根据 XSD 验证 XML 树。These methods use an underlying XmlReader to validate the XML tree against an XSD.

使用 ValidationEventHandler 委托处理验证错误和警告消息。Validation error and warning messages are handled using the ValidationEventHandler delegate. 如果未向这些方法提供事件处理程序,则验证错误将作为 XmlSchemaValidationException公开。If no event handler is provided to these methods, validation errors are exposed as an XmlSchemaValidationException. 验证警告不会导致引发 XmlSchemaValidationExceptionValidation warnings do not cause an XmlSchemaValidationException to be thrown.

其中一些扩展方法可以选择允许填充架构验证后信息集(PSVI)。Some of these extension methods optionally allow population of the post-schema-validation infoset (PSVI).

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

此方法验证 XDocument 是否与 XmlSchemaSet 中的 XSD 相符。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);
static member Validate : System.Xml.Linq.XDocument * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler -> unit

参数

source
XDocument

要验证的 XDocumentThe XDocument to validate.

schemas
XmlSchemaSet

一个作为验证依据的 XmlSchemaSetAn XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

一个 ValidationEventHandler,可用于处理当读取器遇到验证错误时所发生的事件。A ValidationEventHandler for an event that occurs when the reader encounters validation errors. 如果为 null,将在验证错误时引发异常。If null, throws an exception upon validation errors.

异常

出现 XML 架构定义语言 (XSD) 验证错误时引发。Thrown for XML Schema Definition Language (XSD) validation errors.

示例

下面的示例创建一个 XmlSchemaSet,然后针对架构集验证两个 XDocument 对象。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  

注解

此扩展方法验证 XDocument 是否符合 XmlSchemaSet中的架构内容模型。This extension method validates that the XDocument conforms to the schema content model in XmlSchemaSet.

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

此方法验证 XAttribute 是否与指定的 XmlSchemaObjectXmlSchemaSet 相符。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);
static member Validate : System.Xml.Linq.XAttribute * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler -> unit

参数

source
XAttribute

要验证的 XAttributeThe XAttribute to validate.

partialValidationType
XmlSchemaObject

一个 XmlSchemaObject,指定要验证的子树。An XmlSchemaObject that specifies the sub-tree to validate.

schemas
XmlSchemaSet

一个作为验证依据的 XmlSchemaSetAn XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

一个 ValidationEventHandler,可用于处理当读取器遇到验证错误时所发生的事件。A ValidationEventHandler for an event that occurs when the reader encounters validation errors. 如果为 null,将在验证错误时引发异常。If null, throws an exception upon validation errors.

异常

出现 XML 架构定义语言 (XSD) 验证错误时引发。Thrown for XML Schema Definition Language (XSD) validation errors.

示例

  
                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  

注解

您可以使用此方法来验证 XAttribute 是否符合架构。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.

如果传递 validationEventHandler``null,则此方法会在验证错误时引发异常。If you pass null for validationEventHandler, this method raises an exception upon validation errors. 验证警告不会引发异常。Validation warnings will not raise an exception.

若要验证属性,请使用 XmlSchemaObject的实例。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. 通过调用 Validate 扩展方法,添加架构验证后信息集(PSVI)。Add the post-schema-validation infoset (PSVI) by calling the Validate extension method.

  3. 调用 GetSchemaInfo 扩展方法以检索实现 IXmlSchemaInfo的对象。Call the GetSchemaInfo extension method to retrieve an object that implements IXmlSchemaInfo. 从检索的对象中,可以获取 XmlSchemaObjectFrom the retrieved object, you can get an XmlSchemaObject.

具有 XmlSchemaObject的实例后,可以使用此方法来验证特性。After you have an instance of an XmlSchemaObject, you can use this method to validate an attribute.

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

验证 XDocument 是否与 XmlSchemaSet 中的某个 XSD 相符,并且可以选择使用架构验证后信息集 (PSVI) 填充 XML 树。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);
static member Validate : System.Xml.Linq.XDocument * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler * bool -> unit

参数

source
XDocument

要验证的 XDocumentThe XDocument to validate.

schemas
XmlSchemaSet

一个作为验证依据的 XmlSchemaSetAn XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

一个 ValidationEventHandler,可用于处理当读取器遇到验证错误时所发生的事件。A ValidationEventHandler for an event that occurs when the reader encounters validation errors. 如果为 null,将在验证错误时引发异常。If null, throws an exception upon validation errors.

addSchemaInfo
Boolean

一个 Boolean,指示是否填充架构验证后信息集 (PSVI)。A Boolean indicating whether to populate the post-schema-validation infoset (PSVI).

异常

出现 XML 架构定义语言 (XSD) 验证错误时引发。Thrown for XML Schema Definition Language (XSD) validation errors.

示例

下面的示例包含一个 XSD,用于定义具有默认值 Att1 属性的 Child2 元素。The following example contains an XSD that defines the Child2 element with an Att1 attribute with a default value. 成功验证文档后,具有默认值的属性将添加到 XML 树中。After successfully validating the document, the attribute with the default value is added to the XML tree. 请注意,不会将默认属性添加到 doc2中,这不会根据架构进行验证。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>  

下面的示例用 PSVI 填充树。The following example populates the tree with PSVI. 验证后,它会根据 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  

注解

此扩展方法验证 XDocument 是否符合 XmlSchemaSet中的架构内容模型。This extension method validates that the XDocument conforms to the schema content model in XmlSchemaSet.

如果 true``addSchemaInfo,则此方法将用架构验证后信息集(PSVI)填充 XML 树。If addSchemaInfo is true, this method populates the XML tree with the post-schema-validation infoset (PSVI).

可以通过两个步骤,用 PSVI 填充 XML 树。There are two steps to populating the XML tree with the PSVI.

  1. 首先,将批注添加到树中的所有节点,以便对树中的元素或属性调用 Extensions.GetSchemaInfoExtensions.GetSchemaInfoFirst, 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. 其次,将 XSD 中定义的默认元素和属性添加到 XML 树中。Second, default elements and attributes defined in the XSD are added to the XML tree. 通过调用 GetSchemaInfo 方法之一,可以确定是否已将特定元素或特性作为默认元素或特性添加到 XSD。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.

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

此方法验证 XElement 子树是否与指定的 XmlSchemaObjectXmlSchemaSet 相符。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);
static member Validate : System.Xml.Linq.XElement * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler -> unit

参数

source
XElement

要验证的 XElementThe XElement to validate.

partialValidationType
XmlSchemaObject

一个 XmlSchemaObject,指定要验证的子树。An XmlSchemaObject that specifies the sub-tree to validate.

schemas
XmlSchemaSet

一个作为验证依据的 XmlSchemaSetAn XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

一个 ValidationEventHandler,可用于处理当读取器遇到验证错误时所发生的事件。A ValidationEventHandler for an event that occurs when the reader encounters validation errors. 如果为 null,将在验证错误时引发异常。If null, throws an exception upon validation errors.

异常

出现 XML 架构定义语言 (XSD) 验证错误时引发。Thrown for XML Schema Definition Language (XSD) validation errors.

示例

  
                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  

注解

您可以使用此方法验证子树(在其根中具有 XElement)是否符合架构。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.

如果传递 validationEventHandlernull,则此方法会在验证错误时引发异常。If you pass null for validationEventHandler, then this method raises an exception upon validation errors. 验证警告不会引发异常。Validation warnings will not raise an exception.

若要验证子树,请使用 XmlSchemaObject的实例。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. 通过调用 Validate 扩展方法,添加架构验证后信息集(PSVI)。Add the post-schema-validation infoset (PSVI) by calling the Validate extension method.

  3. 调用 GetSchemaInfo 扩展方法以检索实现 IXmlSchemaInfo的对象。Call the GetSchemaInfo extension method to retrieve an object that implements IXmlSchemaInfo. 从检索的对象中,可以获取 XmlSchemaObjectFrom the retrieved object, you can get an XmlSchemaObject.

具有 XmlSchemaObject的实例后,可以使用此方法验证子树。After you have an instance of an XmlSchemaObject, you can use this method to validate an sub-tree.

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

验证 XAttribute 是否与指定的 XmlSchemaObjectXmlSchemaSet 相符,并且可以选择使用架构验证后信息集 (PSVI) 填充 XML 树。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);
static member Validate : System.Xml.Linq.XAttribute * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler * bool -> unit

参数

source
XAttribute

要验证的 XAttributeThe XAttribute to validate.

partialValidationType
XmlSchemaObject

一个 XmlSchemaObject,指定要验证的子树。An XmlSchemaObject that specifies the sub-tree to validate.

schemas
XmlSchemaSet

一个作为验证依据的 XmlSchemaSetAn XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

一个 ValidationEventHandler,可用于处理当读取器遇到验证错误时所发生的事件。A ValidationEventHandler for an event that occurs when the reader encounters validation errors. 如果为 null,将在验证错误时引发异常。If null, throws an exception upon validation errors.

addSchemaInfo
Boolean

一个 Boolean,指示是否填充架构验证后信息集 (PSVI)。A Boolean indicating whether to populate the post-schema-validation infoset (PSVI).

异常

出现 XML 架构定义语言 (XSD) 验证错误时引发。Thrown for XML Schema Definition Language (XSD) validation errors.

示例

  
                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  

注解

您可以使用此方法来验证 XAttribute 是否符合架构。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.

如果 true``addSchemaInfo,则此方法将用架构验证后信息集(PSVI)填充属性。If addSchemaInfo is true, this method populates the attribute with the post-schema-validation infoset (PSVI). 使用 PSVI 填充 XML 树后,可以对已验证的属性调用 Extensions.GetSchemaInfoAfter you have populated the XML tree with the PSVI, you can call Extensions.GetSchemaInfo on the validated attribute. 如果你编写的代码依赖于 GetSchemaInfo返回的数据,则这会很有用。This is useful if you are writing code that relies on data returned by GetSchemaInfo.

如果传递 validationEventHandlernull,则此方法会在验证错误时引发异常。If you pass null for validationEventHandler, then this method raises an exception upon validation errors. 验证警告不会引发异常。Validation warnings will not raise an exception.

若要验证属性,请使用 XmlSchemaObject的实例。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. 通过调用 Validate 扩展方法,添加架构验证后信息集(PSVI)。Add the post-schema-validation infoset (PSVI) by calling the Validate extension method.

  3. 调用 GetSchemaInfo 扩展方法以检索实现 IXmlSchemaInfo的对象。Call the GetSchemaInfo extension method to retrieve an object that implements IXmlSchemaInfo. 从检索的对象中,可以获取 XmlSchemaObjectFrom the retrieved object, you can get an XmlSchemaObject.

具有 XmlSchemaObject的实例后,可以使用此方法来验证特性。After you have an instance of an XmlSchemaObject, you can use this method to validate an attribute.

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

验证 XElement 子树是否与指定的 XmlSchemaObjectXmlSchemaSet 相符,并且可以选择使用架构验证后信息集 (PSVI) 填充 XML 树。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);
static member Validate : System.Xml.Linq.XElement * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler * bool -> unit

参数

source
XElement

要验证的 XElementThe XElement to validate.

partialValidationType
XmlSchemaObject

一个 XmlSchemaObject,指定要验证的子树。An XmlSchemaObject that specifies the sub-tree to validate.

schemas
XmlSchemaSet

一个作为验证依据的 XmlSchemaSetAn XmlSchemaSet to validate against.

validationEventHandler
ValidationEventHandler

一个 ValidationEventHandler,可用于处理当读取器遇到验证错误时所发生的事件。A ValidationEventHandler for an event that occurs when the reader encounters validation errors. 如果为 null,将在验证错误时引发异常。If null, throws an exception upon validation errors.

addSchemaInfo
Boolean

一个 Boolean,指示是否填充架构验证后信息集 (PSVI)。A Boolean indicating whether to populate the post-schema-validation infoset (PSVI).

异常

出现 XML 架构定义语言 (XSD) 验证错误时引发。Thrown for XML Schema Definition Language (XSD) validation errors.

示例

  
                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>  

注解

您可以使用此方法验证子树(在子树的根目录下具有 XElement)是否符合架构。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.

如果 true``addSchemaInfo,则此方法将用架构验证后信息集(PSVI)填充 XML 树。If addSchemaInfo is true, then this method populates the XML tree with the post-schema-validation infoset (PSVI).

用 PSVI 填充 XML 树有两个方面。There are two aspects of populating the XML tree with the PSVI.

首先,将批注添加到树中的所有节点,以便现在可以对树中的元素或属性调用 GetSchemaInfoFirst, 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.

其次,将 XSD 中定义的默认元素和属性添加到 XML 树中。Second, default elements and attributes defined in the XSD are added to the XML tree. 通过调用 GetSchemaInfo 方法之一,可以确定是否已将特定元素或特性作为默认元素或特性添加到 XSD。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.

如果传递 validationEventHandlernull,则此方法会在验证错误时引发异常。If you pass null for validationEventHandler, then this method raises an exception upon validation errors. 验证警告不会引发异常。Validation warnings will not raise an exception.

若要验证子树,请使用 XmlSchemaObject的实例。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. 通过调用 Validate 扩展方法,添加架构验证后信息集(PSVI)。Add the post-schema-validation infoset (PSVI) by calling the Validate extension method.

  3. 调用 GetSchemaInfo 扩展方法以检索实现 IXmlSchemaInfo的对象。Call the GetSchemaInfo extension method to retrieve an object that implements IXmlSchemaInfo. 从检索的对象中,可以获取 XmlSchemaObjectFrom the retrieved object, you can get an XmlSchemaObject.

具有 XmlSchemaObject的实例后,可以使用此方法验证子树。After you have an instance of an XmlSchemaObject, you can use this method to validate a sub-tree..

适用于