Extensions.Validate 메서드

정의

XDocument, XElement 또는 XAttributeXmlSchemaSet에서 XSD를 준수하는지 확인합니다.

오버로드

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

이 메서드는 XDocumentXmlSchemaSet에서 XSD를 준수하는지 확인합니다.

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

이 메서드는 XAttribute가 지정된 XmlSchemaObjectXmlSchemaSet을 준수하는지 확인합니다.

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

XDocumentXmlSchemaSet에서 XSD를 준수하는지 확인하고, 선택적으로 XML 트리를 PSVI(스키마 유효성 검사 이후 정보 집합)로 채울 수 있습니다.

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

이 메서드는 XElement 하위 트리가 지정된 XmlSchemaObjectXmlSchemaSet을 준수하는지 확인합니다.

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

XAttribute가 지정된 XmlSchemaObjectXmlSchemaSet을 준수하는지 확인하고, 선택적으로 XML 트리를 PSVI(스키마 유효성 검사 이후 정보 집합)로 채울 수 있습니다.

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

XElement 하위 트리가 지정된 XmlSchemaObjectXmlSchemaSet을 준수하는지 확인하고, 선택적으로 XML 트리를 PSVI(스키마 유효성 검사 이후 정보 집합)로 채울 수 있습니다.

설명

이러한 메서드는 기본 을 XmlReader 사용하여 XSD에 대해 XML 트리의 유효성을 검사합니다.

유효성 검사 오류 및 경고 메시지는 대리자를 ValidationEventHandler 사용하여 처리됩니다. 이러한 메서드에 이벤트 처리기가 제공되지 않으면 유효성 검사 오류가 로 XmlSchemaValidationException노출됩니다. 유효성 검사 경고로 인해 이 XmlSchemaValidationException throw되지 않습니다.

이러한 확장 메서드 중 일부는 필요에 따라 PSVI(사후 스키마 유효성 검사 정보 세트)의 채우기를 허용합니다.

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

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

이 메서드는 XDocumentXmlSchemaSet에서 XSD를 준수하는지 확인합니다.

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)

매개 변수

source
XDocument

유효성을 검사할 XDocument입니다.

schemas
XmlSchemaSet

유효성을 검사할 XmlSchemaSet입니다.

validationEventHandler
ValidationEventHandler

판독기에서 유효성 검사 오류를 발견했을 때 수행되는 이벤트의 ValidationEventHandler입니다. null인 경우 유효성 검사 오류가 있을 때 예외가 throw됩니다.

예외

XSD(XML 스키마 정의) 언어 유효성 검사 오류가 발생한 경우 throw됩니다.

예제

다음 예제에서는 XmlSchemaSet을 만든 다음 스키마 집합에 대해 두 XDocument 개체의 유효성을 검사합니다. 문서 중 하나는 유효하고 다른 하나는 유효하지 않습니다.

                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  

이 예제는 다음과 같은 출력을 생성합니다.

Validating doc1  
doc1 validated  

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

설명

이 확장 메서드는 의 XDocument 스키마 콘텐츠 모델을 XmlSchemaSet준수하는지 유효성을 검사합니다.

적용 대상

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

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

이 메서드는 XAttribute가 지정된 XmlSchemaObjectXmlSchemaSet을 준수하는지 확인합니다.

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)

매개 변수

source
XAttribute

유효성을 검사할 XAttribute입니다.

partialValidationType
XmlSchemaObject

유효성을 검사할 하위 트리를 지정하는 XmlSchemaObject입니다.

schemas
XmlSchemaSet

유효성을 검사할 XmlSchemaSet입니다.

validationEventHandler
ValidationEventHandler

판독기에서 유효성 검사 오류를 발견했을 때 수행되는 이벤트의 ValidationEventHandler입니다. null인 경우 유효성 검사 오류가 있을 때 예외가 throw됩니다.

예외

XSD(XML 스키마 정의) 언어 유효성 검사 오류가 발생한 경우 throw됩니다.

예제

                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  

이 예제는 다음과 같은 출력을 생성합니다.

Validating doc1 ...  
doc1 validated  

Validating Lang attribute ...  
lang validated  

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

설명

이 메서드를 사용하여 가 스키마를 XAttribute 준수하는지 확인할 수 있습니다. 일반적으로 특성을 수정한 경우 이 메서드를 사용하며 여전히 해당 스키마를 준수하는지 확인하려고 합니다. 전체 문서의 유효성을 검사할 수 있지만 특성의 유효성을 검사하는 데 처리 시간이 덜 걸립니다.

validationEventHandler전달하는 null 경우 이 메서드는 유효성 검사 오류 시 예외를 발생합니다. 유효성 검사 경고는 예외를 발생시키지 않습니다.

특성의 유효성을 검사하려면 인스턴스 XmlSchemaObject를 사용합니다. 다양한 방법으로 이 인스턴스를 가져올 수 있습니다. 쉬운 방법은 다음과 같습니다.

  1. 문서가 스키마를 준수하는지 확인합니다.

  2. 확장 메서드를 호출하여 PSVI(스키마 유효성 검사 후 정보 세트)를 Validate 추가합니다.

  3. 확장 메서드를 GetSchemaInfo 호출하여 를 구현하는 개체를 검색합니다 IXmlSchemaInfo. 검색된 개체에서 를 가져올 XmlSchemaObject수 있습니다.

인스턴스가 있으면 이 메서드를 XmlSchemaObject사용하여 특성의 유효성을 검사할 수 있습니다.

적용 대상

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

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

XDocumentXmlSchemaSet에서 XSD를 준수하는지 확인하고, 선택적으로 XML 트리를 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)

매개 변수

source
XDocument

유효성을 검사할 XDocument입니다.

schemas
XmlSchemaSet

유효성을 검사할 XmlSchemaSet입니다.

validationEventHandler
ValidationEventHandler

판독기에서 유효성 검사 오류를 발견했을 때 수행되는 이벤트의 ValidationEventHandler입니다. null인 경우 유효성 검사 오류가 있을 때 예외가 throw됩니다.

addSchemaInfo
Boolean

PSVI(스키마 유효성 검사 이후 정보 집합)를 채울지 여부를 나타내는 Boolean입니다.

예외

XSD(XML 스키마 정의) 언어 유효성 검사 오류가 발생한 경우 throw됩니다.

예제

다음 예제에는 기본값이 있는 특성을 사용하여 요소를 Att1 정의하는 Child2 XSD가 포함되어 있습니다. 문서의 유효성을 성공적으로 검사한 후 기본값이 있는 특성이 XML 트리에 추가됩니다. 기본 특성은 스키마에 대해 유효성을 doc2검사하지 않는 에 추가되지 않습니다.

                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  

이 예제는 다음과 같은 출력을 생성합니다.

Validating doc1  
doc1 validated  

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

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

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

다음 예제에서는 트리를 PSVI로 채웁니다. 유효성 검사 후 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  

이 예제는 다음과 같은 출력을 생성합니다.

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

설명

이 확장 메서드는 의 XDocument 스키마 콘텐츠 모델을 XmlSchemaSet준수하는지 유효성을 검사합니다.

이 이trueaddSchemaInfo 이 메서드는 XML 트리를 PSVI(스키마 유효성 검사 후 정보 세트)로 채웁니다.

XML 트리를 PSVI로 채우는 두 단계가 있습니다.

  1. 먼저 트리의 모든 노드에 주석이 추가되어 트리의 요소 또는 특성을 호출하거나 Extensions.GetSchemaInfo 호출 Extensions.GetSchemaInfo 할 수 있습니다.

  2. 둘째, XSD에 정의된 기본 요소 및 특성이 XML 트리에 추가됩니다. 메서드 중 GetSchemaInfo 하나를 호출하면 XSD에서 특정 요소 또는 특성이 기본 요소 또는 특성으로 추가되었는지 확인할 수 있습니다.

적용 대상

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

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

이 메서드는 XElement 하위 트리가 지정된 XmlSchemaObjectXmlSchemaSet을 준수하는지 확인합니다.

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)

매개 변수

source
XElement

유효성을 검사할 XElement입니다.

partialValidationType
XmlSchemaObject

유효성을 검사할 하위 트리를 지정하는 XmlSchemaObject입니다.

schemas
XmlSchemaSet

유효성을 검사할 XmlSchemaSet입니다.

validationEventHandler
ValidationEventHandler

판독기에서 유효성 검사 오류를 발견했을 때 수행되는 이벤트의 ValidationEventHandler입니다. null인 경우 유효성 검사 오류가 있을 때 예외가 throw됩니다.

예외

XSD(XML 스키마 정의) 언어 유효성 검사 오류가 발생한 경우 throw됩니다.

예제

                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  

이 예제는 다음과 같은 출력을 생성합니다.

Validating doc1 ...  
doc1 validated  

Validating Child1 after first edit ...  
child1 validated  

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

설명

이 메서드를 사용하여 루트에 있는 하위 트리 XElement 가 스키마를 준수하는지 확인할 수 있습니다. 일반적으로 하위 트리를 수정한 경우 이 메서드를 사용하며 여전히 해당 스키마를 준수하는지 확인하려고 합니다. 전체 문서의 유효성을 검사할 수 있지만 하위 트리의 유효성을 검사하는 데 처리 시간이 덜 걸립니다.

에 를 validationEventHandler전달 null 하면 이 메서드는 유효성 검사 오류 시 예외를 발생합니다. 유효성 검사 경고는 예외를 발생시키지 않습니다.

하위 트리의 유효성을 검사하려면 인스턴스 XmlSchemaObject를 사용합니다. 다양한 방법으로 이 인스턴스를 가져올 수 있습니다. 쉬운 방법은 다음과 같습니다.

  1. 문서가 스키마를 준수하는지 확인합니다.

  2. 확장 메서드를 호출하여 PSVI(스키마 유효성 검사 후 정보 세트)를 Validate 추가합니다.

  3. 확장 메서드를 GetSchemaInfo 호출하여 를 구현하는 개체를 검색합니다 IXmlSchemaInfo. 검색된 개체에서 를 가져올 XmlSchemaObject수 있습니다.

인스턴스가 있으면 이 메서드를 XmlSchemaObject사용하여 하위 트리의 유효성을 검사할 수 있습니다.

적용 대상

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

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

XAttribute가 지정된 XmlSchemaObjectXmlSchemaSet을 준수하는지 확인하고, 선택적으로 XML 트리를 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)

매개 변수

source
XAttribute

유효성을 검사할 XAttribute입니다.

partialValidationType
XmlSchemaObject

유효성을 검사할 하위 트리를 지정하는 XmlSchemaObject입니다.

schemas
XmlSchemaSet

유효성을 검사할 XmlSchemaSet입니다.

validationEventHandler
ValidationEventHandler

판독기에서 유효성 검사 오류를 발견했을 때 수행되는 이벤트의 ValidationEventHandler입니다. null인 경우 유효성 검사 오류가 있을 때 예외가 throw됩니다.

addSchemaInfo
Boolean

PSVI(스키마 유효성 검사 이후 정보 집합)를 채울지 여부를 나타내는 Boolean입니다.

예외

XSD(XML 스키마 정의) 언어 유효성 검사 오류가 발생한 경우 throw됩니다.

예제

                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  

이 예제는 다음과 같은 출력을 생성합니다.

Validating doc1 ...  
doc1 validated  

Validating Lang attribute ...  
lang validated  

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

설명

이 메서드를 사용하여 가 스키마를 XAttribute 준수하는지 확인할 수 있습니다. 일반적으로 특성을 수정한 경우 이 메서드를 사용하며 여전히 해당 스키마를 준수하는지 확인하려고 합니다. 전체 문서의 유효성을 검사할 수 있지만 특성만 유효성을 검사하는 데 처리 시간이 덜 걸립니다.

이 이trueaddSchemaInfo 이 메서드는 특성을 PSVI(사후 스키마 유효성 검사 정보 세트)로 채웁니다. XML 트리를 PSVI로 채운 후 유효성이 검사된 특성에서 를 호출 Extensions.GetSchemaInfo 할 수 있습니다. 이 기능은 에서 반환 GetSchemaInfo된 데이터를 사용하는 코드를 작성하는 경우에 유용합니다.

에 를 validationEventHandler전달하는 null 경우 이 메서드는 유효성 검사 오류 시 예외를 발생합니다. 유효성 검사 경고는 예외를 발생시키지 않습니다.

특성의 유효성을 검사하려면 인스턴스 XmlSchemaObject를 사용합니다. 다양한 방법으로 이 인스턴스를 가져올 수 있습니다. 쉬운 방법은 다음과 같습니다.

  1. 문서가 스키마를 준수하는지 확인합니다.

  2. 확장 메서드를 호출하여 PSVI(사후 스키마 유효성 검사 정보 세트)를 Validate 추가합니다.

  3. 확장 메서드를 GetSchemaInfo 호출하여 를 구현하는 개체를 검색합니다 IXmlSchemaInfo. 검색된 개체에서 를 가져올 XmlSchemaObject수 있습니다.

인스턴스가 있으면 이 메서드를 XmlSchemaObject사용하여 특성의 유효성을 검사할 수 있습니다.

적용 대상

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

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

XElement 하위 트리가 지정된 XmlSchemaObjectXmlSchemaSet을 준수하는지 확인하고, 선택적으로 XML 트리를 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)

매개 변수

source
XElement

유효성을 검사할 XElement입니다.

partialValidationType
XmlSchemaObject

유효성을 검사할 하위 트리를 지정하는 XmlSchemaObject입니다.

schemas
XmlSchemaSet

유효성을 검사할 XmlSchemaSet입니다.

validationEventHandler
ValidationEventHandler

판독기에서 유효성 검사 오류를 발견했을 때 수행되는 이벤트의 ValidationEventHandler입니다. null인 경우 유효성 검사 오류가 있을 때 예외가 throw됩니다.

addSchemaInfo
Boolean

PSVI(스키마 유효성 검사 이후 정보 집합)를 채울지 여부를 나타내는 Boolean입니다.

예외

XSD(XML 스키마 정의) 언어 유효성 검사 오류가 발생한 경우 throw됩니다.

예제

                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  

이 예제는 다음과 같은 출력을 생성합니다.

Validating doc1  
doc1 validated  

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

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

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

설명

이 메서드를 사용하여 하위 트리(하위 트리의 루트에 있는 ) XElement 가 스키마를 준수하는지 확인할 수 있습니다. 일반적으로 하위 트리를 수정한 경우 이 메서드를 사용하며 여전히 해당 스키마를 준수하는지 확인하려고 합니다. 전체 문서의 유효성을 검사할 수 있지만 하위 트리의 유효성을 검사하는 데 처리 시간이 덜 걸립니다.

true이면 addSchemaInfo 이 메서드는 XML 트리를 PSVI(사후 스키마 유효성 검사 정보 세트)로 채웁니다.

XML 트리를 PSVI로 채우는 두 가지 측면이 있습니다.

먼저 트리의 요소 또는 특성에서 를 호출 GetSchemaInfo 할 수 있도록 트리의 모든 노드에 주석이 추가됩니다.

둘째, XSD에 정의된 기본 요소와 특성이 XML 트리에 추가됩니다. 메서드 중 GetSchemaInfo 하나를 호출하여 XSD에서 특정 요소 또는 특성이 기본 요소 또는 특성으로 추가되었는지 확인할 수 있습니다.

에 를 validationEventHandler전달하는 null 경우 이 메서드는 유효성 검사 오류 시 예외를 발생합니다. 유효성 검사 경고는 예외를 발생시키지 않습니다.

하위 트리의 유효성을 검사하려면 인스턴스 XmlSchemaObject를 사용합니다. 다양한 방법으로 이 인스턴스를 가져올 수 있습니다. 쉬운 방법은 다음과 같습니다.

  1. 문서가 스키마를 준수하는지 확인합니다.

  2. 확장 메서드를 호출하여 PSVI(사후 스키마 유효성 검사 정보 세트)를 Validate 추가합니다.

  3. 확장 메서드를 GetSchemaInfo 호출하여 를 구현하는 개체를 검색합니다 IXmlSchemaInfo. 검색된 개체에서 를 가져올 XmlSchemaObject수 있습니다.

인스턴스가 있으면 이 메서드를 XmlSchemaObject사용하여 하위 트리의 유효성을 검사할 수 있습니다.

적용 대상