Extensions.Validate Yöntem

Tanım

bir XDocument, veya XElementXAttribute öğesinin bir içindeki XSD'ye XmlSchemaSetuygun olduğunu doğrular.

Aşırı Yüklemeler

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

Bu yöntem, içindeki bir XDocument XSD'ye XmlSchemaSetuygun olduğunu doğrular.

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Bu yöntem, belirtilen XAttribute XmlSchemaObject ve XmlSchemaSetile uyumlu olduğunu doğrular.

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

içindeki bir XDocument XSD'ye XmlSchemaSetuygun olduğunu doğrular ve isteğe bağlı olarak XML ağacını şema doğrulama sonrası bilgi kümesi (PSVI) ile doldurur.

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Bu yöntem, bir XElement alt ağacın belirtilen XmlSchemaObject ve XmlSchemaSetile uyumlu olduğunu doğrular.

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

bir XAttribute öğesinin belirtilen XmlSchemaObject ve XmlSchemaSetile uyumlu olduğunu doğrular ve isteğe bağlı olarak XML ağacını şema doğrulama sonrası bilgi kümesi (PSVI) ile doldurur.

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

Bir XElement alt ağacın belirtilen XmlSchemaObject ve ile uyumlu olduğunu doğrular ve XmlSchemaSetisteğe bağlı olarak XML ağacını şema sonrası doğrulama bilgi kümesi (PSVI) ile doldurur.

Açıklamalar

Bu yöntemler, XSD'ye karşı XML ağacını doğrulamak için temel alınan XmlReader bir kullanır.

Doğrulama hatası ve uyarı iletileri temsilci kullanılarak ValidationEventHandler işlenir. Bu yöntemlere hiçbir olay işleyicisi sağlanmadıysa, doğrulama hataları olarak XmlSchemaValidationExceptionortaya çıkar. Doğrulama uyarıları bir XmlSchemaValidationException atlanmasına neden olmaz.

Bu uzantı yöntemlerinden bazıları isteğe bağlı olarak şema doğrulama sonrası bilgi kümesinin (PSVI) popülasyonunu sağlar.

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

Bu yöntem, içindeki bir XDocument XSD'ye XmlSchemaSetuygun olduğunu doğrular.

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)

Parametreler

source
XDocument

XDocument doğrulanır.

schemas
XmlSchemaSet

Doğrulanması gereken bir XmlSchemaSet .

validationEventHandler
ValidationEventHandler

ValidationEventHandler Okuyucu doğrulama hatalarıyla karşılaştığında oluşan bir olay için. ise null, doğrulama hataları üzerine bir özel durum oluşturur.

Özel durumlar

XML Şema Tanımlama Dili (XSD) doğrulama hataları için oluşturuldu.

Örnekler

Aşağıdaki örnek bir XmlSchemaSetoluşturur ve ardından iki XDocument nesneyi şema kümesine göre doğrular. Belgelerden biri geçerli, diğeri geçerli değil.

                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  

Bu örnek aşağıdaki çıkışı oluşturur:

Validating doc1  
doc1 validated  

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

Açıklamalar

Bu uzantı yöntemi, içindeki XDocument şema içerik modeline XmlSchemaSetuygun olduğunu doğrular.

Şunlara uygulanır

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Bu yöntem, belirtilen XAttribute XmlSchemaObject ve XmlSchemaSetile uyumlu olduğunu doğrular.

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)

Parametreler

source
XAttribute

XAttribute doğrulanır.

partialValidationType
XmlSchemaObject

XmlSchemaObject Doğrulanması gereken alt ağacı belirten bir.

schemas
XmlSchemaSet

Doğrulanması gereken bir XmlSchemaSet .

validationEventHandler
ValidationEventHandler

ValidationEventHandler Okuyucu doğrulama hatalarıyla karşılaştığında oluşan bir olay için. ise null, doğrulama hataları üzerine bir özel durum oluşturur.

Özel durumlar

XML Şema Tanımlama Dili (XSD) doğrulama hataları için oluşturuldu.

Örnekler

                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  

Bu örnek aşağıdaki çıkışı oluşturur:

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  

Açıklamalar

Bir şemaya uygun olduğunu XAttribute doğrulamak için bu yöntemi kullanabilirsiniz. Bu yöntemi genellikle bir özniteliği değiştirdiğinizde ve yine de şemasına uygun olduğundan emin olmak istediğinizde kullanırsınız. Belgenin tamamını doğrulayabilirsiniz, ancak yalnızca özniteliğini doğrulamak daha az işlem süresi alır.

için validationEventHandlergeçirirseniznull, bu yöntem doğrulama hataları üzerine bir özel durum oluşturur. Doğrulama uyarıları özel durum oluşturmaz.

Bir özniteliği doğrulamak için örneğini XmlSchemaObjectkullanırsınız. Bu örneği çeşitli yollarla edinebilirsiniz. Kolay bir yol aşağıdaki gibidir:

  1. Belgenin şemaya uygun olduğunu doğrulayın.

  2. Uzantı yöntemini çağırarak Validate şema doğrulama sonrası bilgi kümesini (PSVI) ekleyin.

  3. uygulayan GetSchemaInfo bir nesneyi almak için uzantı yöntemini çağırın IXmlSchemaInfo. Alınan nesneden bir XmlSchemaObjectalabilirsiniz.

bir örneğine XmlSchemaObjectsahip olduktan sonra, bir özniteliği doğrulamak için bu yöntemi kullanabilirsiniz.

Şunlara uygulanır

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

içindeki bir XDocument XSD'ye XmlSchemaSetuygun olduğunu doğrular ve isteğe bağlı olarak XML ağacını şema doğrulama sonrası bilgi kümesi (PSVI) ile doldurur.

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)

Parametreler

source
XDocument

XDocument doğrulanır.

schemas
XmlSchemaSet

Doğrulanması gereken bir XmlSchemaSet .

validationEventHandler
ValidationEventHandler

ValidationEventHandler Okuyucu doğrulama hatalarıyla karşılaştığında oluşan bir olay için. ise null, doğrulama hataları üzerine bir özel durum oluşturur.

addSchemaInfo
Boolean

Boolean Şema doğrulama sonrası bilgi kümesinin (PSVI) doldurulup doldurulmayacağını belirten bir.

Özel durumlar

XML Şema Tanımlama Dili (XSD) doğrulama hataları için oluşturuldu.

Örnekler

Aşağıdaki örnek, öğesini varsayılan değere Child2 sahip bir öznitelikle tanımlayan bir Att1 XSD içerir. Belge başarıyla doğruladıktan sonra, varsayılan değere sahip öznitelik XML ağacına eklenir. Varsayılan özniteliğin şemasında doc2doğrulanmamış olan öğesine eklenmediğini unutmayın.

                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  

Bu örnek aşağıdaki çıkışı oluşturur:

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>  

Aşağıdaki örnek ağacı PSVI ile doldurur. Doğrulamadan sonra, ağaçtaki PSVI'ye göre geçersiz olan tüm öğeleri ve öznitelikleri yazdırır.

                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  

Bu örnek aşağıdaki çıkışı oluşturur:

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  

Açıklamalar

Bu uzantı yöntemi, içindeki XDocument şema içerik modeline XmlSchemaSetuygun olduğunu doğrular.

ise addSchemaInfo true, bu yöntem XML ağacını şema doğrulama sonrası bilgi kümesi (PSVI) ile doldurur.

XML ağacını PSVI ile doldurmanın iki adımı vardır.

  1. İlk olarak, ağaçtaki bir öğeyi veya Extensions.GetSchemaInfo özniteliği çağırmanızı Extensions.GetSchemaInfo sağlamak için ağaçtaki tüm düğümlere bir ek açıklama eklenir.

  2. İkinci olarak, XSD'de tanımlanan varsayılan öğeler ve öznitelikler XML ağacına eklenir. Yöntemlerden birini GetSchemaInfo çağırarak, XSD'den varsayılan öğe veya öznitelik olarak belirli bir öğenin veya özniteliğin eklenip eklenmediğini belirleyebilirsiniz.

Şunlara uygulanır

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Bu yöntem, bir XElement alt ağacın belirtilen XmlSchemaObject ve XmlSchemaSetile uyumlu olduğunu doğrular.

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)

Parametreler

source
XElement

XElement doğrulanır.

partialValidationType
XmlSchemaObject

XmlSchemaObject Doğrulanması gereken alt ağacı belirten bir.

schemas
XmlSchemaSet

Doğrulanması gereken bir XmlSchemaSet .

validationEventHandler
ValidationEventHandler

ValidationEventHandler Okuyucu doğrulama hatalarıyla karşılaştığında oluşan bir olay için. ise null, doğrulama hataları üzerine bir özel durum oluşturur.

Özel durumlar

XML Şema Tanım Dili (XSD) doğrulama hataları için oluşturuldu.

Örnekler

                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  

Bu örnek aşağıdaki çıkışı oluşturur:

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  

Açıklamalar

Bir alt ağacın (kökünde bir XElement bulunan) bir şemaya uygun olduğunu doğrulamak için bu yöntemi kullanabilirsiniz. Bu yöntemi genellikle bir alt ağacı değiştirdiğinizde ve yine de şemasına uygun olduğundan emin olmak istediğinizde kullanırsınız. Belgenin tamamını doğrulayabilirsiniz, ancak yalnızca bir alt ağacı doğrulamak daha kısa sürer.

için validationEventHandlergeçirirseniznull, bu yöntem doğrulama hataları üzerine bir özel durum oluşturur. Doğrulama uyarıları özel durum oluşturmaz.

Bir alt ağacı doğrulamak için örneğini XmlSchemaObjectkullanırsınız. Bu örneği çeşitli yollarla elde edebilirsiniz. Kolay bir yol aşağıdaki gibidir:

  1. Belgenin şemaya uygun olduğunu doğrulayın.

  2. Uzantı yöntemini çağırarak Validate şema doğrulama sonrası bilgi kümesini (PSVI) ekleyin.

  3. uygulayan GetSchemaInfo bir nesneyi almak için uzantı yöntemini çağırın IXmlSchemaInfo. Alınan nesneden bir XmlSchemaObjectalabilirsiniz.

bir örneğine XmlSchemaObjectsahip olduktan sonra, bir alt ağacı doğrulamak için bu yöntemi kullanabilirsiniz.

Şunlara uygulanır

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

bir XAttribute öğesinin belirtilen XmlSchemaObject ve XmlSchemaSetile uyumlu olduğunu doğrular ve isteğe bağlı olarak XML ağacını şema doğrulama sonrası bilgi kümesi (PSVI) ile doldurur.

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)

Parametreler

source
XAttribute

XAttribute doğrulanır.

partialValidationType
XmlSchemaObject

XmlSchemaObject Doğrulanması gereken alt ağacı belirten bir.

schemas
XmlSchemaSet

Doğrulanması XmlSchemaSet gereken bir.

validationEventHandler
ValidationEventHandler

ValidationEventHandler Okuyucu doğrulama hatalarıyla karşılaştığında oluşan bir olay için. ise null, doğrulama hatalarında bir özel durum oluşturur.

addSchemaInfo
Boolean

Boolean Şema doğrulama sonrası bilgi kümesinin (PSVI) doldurulup doldurulmayacağını belirten bir.

Özel durumlar

XML Şema Tanım Dili (XSD) doğrulama hataları için oluşturuldu.

Örnekler

                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  

Bu örnek aşağıdaki çıkışı oluşturur:

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  

Açıklamalar

Bir şemaya uygun olduğunu XAttribute doğrulamak için bu yöntemi kullanabilirsiniz. Bu yöntemi genellikle bir özniteliği değiştirdiğinizde ve hala şemasına uygun olduğundan emin olmak istediğinizde kullanırsınız. Belgenin tamamını doğrulayabilirsiniz, ancak yalnızca özniteliği doğrulamak daha az işlem süresi alır.

ise addSchemaInfo true, bu yöntem özniteliği şema sonrası doğrulama bilgi kümesi (PSVI) ile doldurur. XML ağacını PSVI ile doldurduktan sonra, doğrulanmış özniteliği çağırabilirsiniz Extensions.GetSchemaInfo . tarafından döndürülen GetSchemaInfoverilere dayalı kod yazıyorsanız bu yararlı olur.

için validationEventHandlergeçirirseniznull, bu yöntem doğrulama hataları üzerine bir özel durum oluşturur. Doğrulama uyarıları özel durum oluşturmaz.

Bir özniteliği doğrulamak için örneğini XmlSchemaObjectkullanırsınız. Bu örneği çeşitli yollarla elde edebilirsiniz. Kolay bir yol aşağıdaki gibidir:

  1. Belgenin şemaya uygun olduğunu doğrulayın.

  2. Uzantı yöntemini çağırarak Validate şema doğrulama sonrası bilgi kümesini (PSVI) ekleyin.

  3. uygulayan GetSchemaInfo bir nesneyi almak için uzantı yöntemini çağırın IXmlSchemaInfo. Alınan nesneden bir XmlSchemaObjectalabilirsiniz.

bir örneğine XmlSchemaObjectsahip olduktan sonra, bir özniteliği doğrulamak için bu yöntemi kullanabilirsiniz.

Şunlara uygulanır

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

Bir XElement alt ağacın belirtilen XmlSchemaObject ve ile uyumlu olduğunu doğrular ve XmlSchemaSetisteğe bağlı olarak XML ağacını şema sonrası doğrulama bilgi kümesi (PSVI) ile doldurur.

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)

Parametreler

source
XElement

XElement doğrulanır.

partialValidationType
XmlSchemaObject

XmlSchemaObject Doğrulanması gereken alt ağacı belirten bir.

schemas
XmlSchemaSet

Doğrulanması XmlSchemaSet gereken bir.

validationEventHandler
ValidationEventHandler

ValidationEventHandler Okuyucu doğrulama hatalarıyla karşılaştığında oluşan bir olay için. ise null, doğrulama hatalarında bir özel durum oluşturur.

addSchemaInfo
Boolean

Boolean Şema doğrulama sonrası bilgi kümesinin (PSVI) doldurulup doldurulmayacağını belirten bir.

Özel durumlar

XML Şema Tanım Dili (XSD) doğrulama hataları için oluşturuldu.

Örnekler

                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  

Bu örnek aşağıdaki çıkışı oluşturur:

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>  

Açıklamalar

Bir alt ağacın (alt ağacın kökünde bir XElement ile) bir şemaya uygun olduğunu doğrulamak için bu yöntemi kullanabilirsiniz. Bu yöntemi genellikle bir alt ağacı değiştirdiğinizde ve yine de şemasına uygun olduğundan emin olmak istediğinizde kullanırsınız. Belgenin tamamını doğrulayabilirsiniz, ancak yalnızca bir alt ağacı doğrulamak daha az işlem süresi alır.

ise addSchemaInfo true, bu yöntem XML ağacını şema doğrulama sonrası bilgi kümesi (PSVI) ile doldurur.

XML ağacını PSVI ile doldurmanın iki yönü vardır.

İlk olarak, ağaçtaki tüm düğümlere artık ağaçtaki bir öğe veya özniteliği çağırabileceğiniz GetSchemaInfo bir ek açıklama eklenir.

İkinci olarak, XSD'de tanımlanan varsayılan öğeler ve öznitelikler XML ağacına eklenir. Yöntemlerden birini GetSchemaInfo çağırarak, XSD'den belirli bir öğenin veya özniteliğin varsayılan öğe veya öznitelik olarak eklenip eklenmediğini belirleyebilirsiniz.

için validationEventHandlergeçirirseniznull, bu yöntem doğrulama hataları üzerine bir özel durum oluşturur. Doğrulama uyarıları özel durum oluşturmaz.

Bir alt ağacı doğrulamak için örneğini XmlSchemaObjectkullanırsınız. Bu örneği çeşitli yollarla elde edebilirsiniz. Kolay bir yol aşağıdaki gibidir:

  1. Belgenin şemaya uygun olduğunu doğrulayın.

  2. Uzantı yöntemini çağırarak Validate şema doğrulama sonrası bilgi kümesini (PSVI) ekleyin.

  3. uygulayan GetSchemaInfo bir nesneyi almak için uzantı yöntemini çağırın IXmlSchemaInfo. Alınan nesneden bir XmlSchemaObjectalabilirsiniz.

bir örneğine XmlSchemaObjectsahip olduktan sonra, bir alt ağacı doğrulamak için bu yöntemi kullanabilirsiniz..

Şunlara uygulanır