Extensions.Validate Metoda

Definicja

Sprawdza, czy element XDocument, lub XElementXAttribute jest zgodny z XSD w elemecie XmlSchemaSet.

Przeciążenia

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

Ta metoda sprawdza, czy element XDocument jest zgodny z XSD w elemecie XmlSchemaSet.

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Ta metoda sprawdza, czy element XAttribute jest zgodny z określonym XmlSchemaObject i .XmlSchemaSet

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

Sprawdza, czy element XDocument jest zgodny z XSD w XmlSchemaSetpliku , opcjonalnie wypełnia drzewo XML przy użyciu zestawu informacji po weryfikacji schematu (PSVI).

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Ta metoda sprawdza, czy XElement drzewo podrzędne jest zgodne z określonym XmlSchemaObject i .XmlSchemaSet

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

Sprawdza, czy element XAttribute jest zgodny z określonym XmlSchemaObject i XmlSchemaSet, opcjonalnie wypełnia drzewo XML za pomocą zestawu informacji po weryfikacji schematu (PSVI).

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

Sprawdza, czy XElement drzewo podrzędne jest zgodne z określonym XmlSchemaObject i XmlSchemaSet, opcjonalnie wypełnianie drzewa XML za pomocą zestawu informacji po weryfikacji schematu (PSVI).

Uwagi

Te metody używają bazowego XmlReader elementu do weryfikowania drzewa XML względem XSD.

Komunikaty o błędach walidacji i ostrzeżeniach są obsługiwane przy użyciu delegata ValidationEventHandler . Jeśli program obsługi zdarzeń nie zostanie dostarczony do tych metod, błędy sprawdzania poprawności są widoczne jako XmlSchemaValidationException. Ostrzeżenia sprawdzania poprawności nie powodują zgłoszenia.XmlSchemaValidationException

Niektóre z tych metod rozszerzeń opcjonalnie umożliwiają populację zestawu informacji po weryfikacji schematu (PSVI).

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs

Ta metoda sprawdza, czy element XDocument jest zgodny z XSD w elemecie XmlSchemaSet.

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

Parametry

source
XDocument

Element XDocument do weryfikacji.

schemas
XmlSchemaSet

Element XmlSchemaSet do weryfikacji.

validationEventHandler
ValidationEventHandler

Element ValidationEventHandler dla zdarzenia, które występuje, gdy czytelnik napotka błędy walidacji. W przypadku null, zgłasza wyjątek podczas sprawdzania poprawności.

Wyjątki

Zgłaszane błędy sprawdzania poprawności języka XML Schema Definition Language (XSD).

Przykłady

Poniższy przykład tworzy obiekt XmlSchemaSet, a następnie weryfikuje dwa XDocument obiekty względem zestawu schematów. Jeden z dokumentów jest prawidłowy, a drugi nie.

                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  

Ten przykład generuje następujące wyniki:

Validating doc1  
doc1 validated  

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

Uwagi

Ta metoda rozszerzenia sprawdza, czy XDocument model zawartości schematu jest zgodny z modelem zawartości schematu w programie XmlSchemaSet.

Dotyczy

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs

Ta metoda sprawdza, czy element XAttribute jest zgodny z określonym XmlSchemaObject i .XmlSchemaSet

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

Parametry

source
XAttribute

Element XAttribute do weryfikacji.

partialValidationType
XmlSchemaObject

Element XmlSchemaObject określający drzewo podrzędne do zweryfikowania.

schemas
XmlSchemaSet

Element XmlSchemaSet do weryfikacji.

validationEventHandler
ValidationEventHandler

Element ValidationEventHandler dla zdarzenia, które występuje, gdy czytelnik napotka błędy walidacji. W przypadku null, zgłasza wyjątek podczas sprawdzania poprawności.

Wyjątki

Zgłaszane błędy sprawdzania poprawności języka XML Schema Definition Language (XSD).

Przykłady

                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  

Ten przykład generuje następujące wyniki:

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  

Uwagi

Za pomocą tej metody można sprawdzić, czy XAttribute element jest zgodny ze schematem. Zazwyczaj używasz tej metody podczas modyfikowania atrybutu i chcesz upewnić się, że nadal jest ona zgodna ze schematem. Można zweryfikować cały dokument, ale weryfikacja atrybutu zajmuje mniej czasu przetwarzania.

W przypadku przekazania null dla validationEventHandlermetody ta metoda zgłasza wyjątek po błędach walidacji. Ostrzeżenia sprawdzania poprawności nie spowodują wystąpienia wyjątku.

Aby zweryfikować atrybut, należy użyć wystąpienia klasy XmlSchemaObject. To wystąpienie można uzyskać na różne sposoby. Prosty sposób jest następujący:

  1. Sprawdź, czy dokument jest zgodny ze schematem.

  2. Dodaj zestaw informacji po weryfikacji schematu (PSVI), wywołując metodę Validate rozszerzenia.

  3. Wywołaj metodę rozszerzenia, GetSchemaInfo aby pobrać obiekt, który implementuje IXmlSchemaInfoelement . Z pobranego obiektu można uzyskać obiekt XmlSchemaObject.

Po wystąpieniu XmlSchemaObjectklasy można użyć tej metody do zweryfikowania atrybutu.

Dotyczy

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs

Sprawdza, czy element XDocument jest zgodny z XSD w XmlSchemaSetpliku , opcjonalnie wypełnia drzewo XML przy użyciu zestawu informacji po weryfikacji schematu (PSVI).

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

Parametry

source
XDocument

Element XDocument do weryfikacji.

schemas
XmlSchemaSet

Element XmlSchemaSet do weryfikacji.

validationEventHandler
ValidationEventHandler

Element ValidationEventHandler dla zdarzenia, które występuje, gdy czytelnik napotka błędy walidacji. W przypadku null, zgłasza wyjątek podczas sprawdzania poprawności.

addSchemaInfo
Boolean

Element Boolean wskazujący, czy należy wypełnić zestaw informacji po weryfikacji schematu (PSVI).

Wyjątki

Zgłaszane błędy sprawdzania poprawności języka XML Schema Definition Language (XSD).

Przykłady

Poniższy przykład zawiera XSD, który definiuje Child2 element z Att1 atrybutem z wartością domyślną. Po pomyślnym zweryfikowaniu dokumentu atrybut z wartością domyślną zostanie dodany do drzewa XML. Należy pamiętać, że atrybut domyślny nie jest dodawany do doc2elementu , który nie sprawdza poprawności względem schematu.

                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  

Ten przykład generuje następujące wyniki:

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>  

Poniższy przykład wypełnia drzewo ciągiem PSVI. Po weryfikacji wyświetla wszystkie elementy i atrybuty w drzewie, które są nieprawidłowe zgodnie z 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  

Ten przykład generuje następujące wyniki:

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  

Uwagi

Ta metoda rozszerzenia sprawdza, czy XDocument model zawartości schematu jest zgodny z modelem zawartości schematu w programie XmlSchemaSet.

Jeśli addSchemaInfo jest trueto , ta metoda wypełnia drzewo XML zestawem informacji po weryfikacji schematu (PSVI).

Istnieją dwa kroki wypełniania drzewa XML przy użyciu programu PSVI.

  1. Najpierw adnotacja jest dodawana do wszystkich węzłów w drzewie, aby umożliwić wywołanie Extensions.GetSchemaInfo elementu lub Extensions.GetSchemaInfo atrybutu w drzewie.

  2. Po drugie, domyślne elementy i atrybuty zdefiniowane w XSD są dodawane do drzewa XML. Wywołując jedną z GetSchemaInfo metod, można określić, czy określony element lub atrybut został dodany z XSD jako domyślny element lub atrybut.

Dotyczy

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs

Ta metoda sprawdza, czy XElement drzewo podrzędne jest zgodne z określonym XmlSchemaObject i .XmlSchemaSet

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

Parametry

source
XElement

Element XElement do weryfikacji.

partialValidationType
XmlSchemaObject

Element XmlSchemaObject określający drzewo podrzędne do zweryfikowania.

schemas
XmlSchemaSet

Element XmlSchemaSet do weryfikacji.

validationEventHandler
ValidationEventHandler

Element ValidationEventHandler dla zdarzenia, które występuje, gdy czytelnik napotka błędy walidacji. W przypadku null, zgłasza wyjątek podczas sprawdzania poprawności.

Wyjątki

Zgłaszane błędy sprawdzania poprawności języka XML Schema Definition Language (XSD).

Przykłady

                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  

Ten przykład generuje następujące wyniki:

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  

Uwagi

Za pomocą tej metody można sprawdzić, czy drzewo podrzędne (z elementem XElement w katalogu głównym) jest zgodne ze schematem. Ta metoda jest zwykle używana podczas modyfikowania podzadrzewa i chcesz się upewnić, że nadal jest ona zgodna ze schematem. Można zweryfikować cały dokument, ale weryfikacja tylko drzewa podrzędnego zajmuje mniej czasu przetwarzania.

W przypadku przekazania null dla validationEventHandlermetody ta metoda zgłasza wyjątek podczas sprawdzania poprawności. Ostrzeżenia sprawdzania poprawności nie spowodują wystąpienia wyjątku.

Aby zweryfikować drzewo podrzędne, należy użyć wystąpienia klasy XmlSchemaObject. To wystąpienie można uzyskać na różne sposoby. Prosty sposób jest następujący:

  1. Sprawdź, czy dokument jest zgodny ze schematem.

  2. Dodaj zestaw informacji po weryfikacji schematu (PSVI), wywołując metodę Validate rozszerzenia.

  3. Wywołaj metodę rozszerzenia, GetSchemaInfo aby pobrać obiekt, który implementuje IXmlSchemaInfoelement . Z pobranego obiektu można uzyskać obiekt XmlSchemaObject.

Po wystąpieniu XmlSchemaObjectklasy można użyć tej metody do zweryfikowania podzadrzewa.

Dotyczy

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

Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs

Sprawdza, czy element XAttribute jest zgodny z określonym XmlSchemaObject i XmlSchemaSet, opcjonalnie wypełnia drzewo XML za pomocą zestawu informacji po weryfikacji schematu (PSVI).

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

Parametry

source
XAttribute

Element XAttribute do weryfikacji.

partialValidationType
XmlSchemaObject

Element XmlSchemaObject określający drzewo podrzędne do zweryfikowania.

schemas
XmlSchemaSet

Element XmlSchemaSet do weryfikacji.

validationEventHandler
ValidationEventHandler

Element ValidationEventHandler dla zdarzenia, które występuje, gdy czytelnik napotka błędy walidacji. W przypadku null, zgłasza wyjątek podczas sprawdzania poprawności.

addSchemaInfo
Boolean

Element Boolean wskazujący, czy należy wypełnić zestaw informacji po weryfikacji schematu (PSVI).

Wyjątki

Zgłaszane błędy sprawdzania poprawności języka XML Schema Definition Language (XSD).

Przykłady

                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  

Ten przykład generuje następujące wyniki:

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  

Uwagi

Za pomocą tej metody można sprawdzić, czy XAttribute element jest zgodny ze schematem. Zazwyczaj używasz tej metody podczas modyfikowania atrybutu i chcesz upewnić się, że nadal jest ona zgodna ze schematem. Można zweryfikować cały dokument, ale weryfikacja atrybutu zajmuje mniej czasu przetwarzania.

Jeśli addSchemaInfo parametr ma truewartość , ta metoda wypełnia atrybut zestawem informacji po weryfikacji schematu (PSVI). Po wypełnieniu drzewa XML ciągiem PSVI można wywołać Extensions.GetSchemaInfo atrybut zweryfikowany. Jest to przydatne, jeśli piszesz kod, który opiera się na danych zwracanych przez GetSchemaInfo.

W przypadku przekazania null dla validationEventHandlermetody ta metoda zgłasza wyjątek podczas sprawdzania poprawności. Ostrzeżenia sprawdzania poprawności nie spowodują wystąpienia wyjątku.

Aby zweryfikować atrybut, należy użyć wystąpienia klasy XmlSchemaObject. To wystąpienie można uzyskać na różne sposoby. Prosty sposób jest następujący:

  1. Sprawdź, czy dokument jest zgodny ze schematem.

  2. Dodaj zestaw informacji po weryfikacji schematu (PSVI), wywołując metodę Validate rozszerzenia.

  3. Wywołaj metodę rozszerzenia, GetSchemaInfo aby pobrać obiekt, który implementuje IXmlSchemaInfoelement . Z pobranego obiektu można uzyskać obiekt XmlSchemaObject.

Po wystąpieniu XmlSchemaObjectklasy można użyć tej metody do zweryfikowania atrybutu.

Dotyczy

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

Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs
Źródło:
XNodeValidator.cs

Sprawdza, czy XElement drzewo podrzędne jest zgodne z określonym XmlSchemaObject i XmlSchemaSet, opcjonalnie wypełnianie drzewa XML za pomocą zestawu informacji po weryfikacji schematu (PSVI).

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

Parametry

source
XElement

Element XElement do weryfikacji.

partialValidationType
XmlSchemaObject

Element XmlSchemaObject określający drzewo podrzędne do zweryfikowania.

schemas
XmlSchemaSet

Element XmlSchemaSet do weryfikacji.

validationEventHandler
ValidationEventHandler

Element ValidationEventHandler dla zdarzenia, które występuje, gdy czytelnik napotka błędy walidacji. W przypadku null, zgłasza wyjątek podczas sprawdzania poprawności.

addSchemaInfo
Boolean

Element Boolean wskazujący, czy należy wypełnić zestaw informacji po weryfikacji schematu (PSVI).

Wyjątki

Zgłaszane błędy sprawdzania poprawności języka XML Schema Definition Language (XSD).

Przykłady

                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  

Ten przykład generuje następujące wyniki:

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>  

Uwagi

Za pomocą tej metody można sprawdzić, czy drzewo podrzędne (z elementem XElement głównym drzewa podrzędnego) jest zgodne ze schematem. Ta metoda jest zwykle używana podczas modyfikowania podzadrzewa i chcesz się upewnić, że nadal jest ona zgodna ze schematem. Można zweryfikować cały dokument, ale weryfikacja tylko drzewa podrzędnego zajmuje mniej czasu przetwarzania.

Jeśli addSchemaInfo ma truewartość , ta metoda wypełnia drzewo XML zestawem informacji po weryfikacji schematu (PSVI).

Istnieją dwa aspekty wypełniania drzewa XML przy użyciu programu PSVI.

Po pierwsze adnotacja jest dodawana do wszystkich węzłów w drzewie, tak aby można było teraz wywołać GetSchemaInfo element lub atrybut w drzewie.

Po drugie, domyślne elementy i atrybuty zdefiniowane w XSD są dodawane do drzewa XML. Wywołując jedną z GetSchemaInfo metod, można określić, czy określony element lub atrybut został dodany z XSD jako domyślny element lub atrybut.

W przypadku przekazania null dla validationEventHandlermetody ta metoda zgłasza wyjątek podczas sprawdzania poprawności. Ostrzeżenia sprawdzania poprawności nie spowodują wystąpienia wyjątku.

Aby zweryfikować drzewo podrzędne, należy użyć wystąpienia klasy XmlSchemaObject. To wystąpienie można uzyskać na różne sposoby. Prosty sposób jest następujący:

  1. Sprawdź, czy dokument jest zgodny ze schematem.

  2. Dodaj zestaw informacji po weryfikacji schematu (PSVI), wywołując metodę Validate rozszerzenia.

  3. Wywołaj metodę rozszerzenia, GetSchemaInfo aby pobrać obiekt, który implementuje IXmlSchemaInfoelement . Z pobranego obiektu można uzyskać obiekt XmlSchemaObject.

Po wystąpieniu XmlSchemaObjectklasy można użyć tej metody do zweryfikowania podzadrzewa.

Dotyczy