다음을 통해 공유


XmlSchemaSet을 사용하여 XSD(XML 스키마) 유효성 검사

XmlSchemaSet의 XSD(XML 스키마 정의 언어) 스키마에 대해 XML 문서의 유효성을 검사할 수 있습니다.

XML 문서 유효성 검사

Create 클래스의 XmlReader 메서드를 사용하여 XML 문서의 유효성을 검사할 수 있습니다. XML 문서의 유효성을 검사하려면 XML 문서의 유효성을 검사하는 데 사용할 XSD(XML 스키마 정의 언어) 스키마가 포함된 XmlReaderSettings 개체를 만듭니다.

참고 항목

System.Xml.Schema 네임스페이스에는 LINQ to XML(C#)LINQ to XML(Visual Basic)을 사용할 때 XSD 파일에 대한 XML 트리의 유효성을 쉽게 검사할 수 있도록 하는 확장 메서드가 포함되어 있습니다. LINQ to XML을 사용하여 XML 문서의 유효성을 검사하는 방법에 대한 자세한 내용은 XSD(LINQ to XML)를 사용하여 유효성을 검사하는 방법(C#)XSD(LINQ to XML)를 사용하여 유효성을 검사하는 방법(Visual Basic)을 참조하세요.

개별 스키마 또는 스키마 집합(XmlSchemaSet) 중 하나를 XmlSchemaSetAdd 메서드에 대한 매개 변수로 전달하여 개별 스키마 또는 스키마 집합을 XmlSchemaSet에 추가할 수 있습니다. 문서 유효성을 확인할 때 문서의 대상 네임스페이스는 스키마 집합에 있는 스키마의 대상 네임스페이스와 일치해야 합니다.

다음은 XML 문서 예제입니다.

<bookstore xmlns="http://www.contoso.com/books">
  <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

다음은 XML 문서 예제의 유효성을 검사하는 스키마입니다.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.contoso.com/books" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="bookstore">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="unbounded" name="book">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="title" type="xs:string" />
                            <xs:element name="author">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element minOccurs="0" name="name" type="xs:string" />
                                        <xs:element minOccurs="0" name="first-name" type="xs:string" />
                                        <xs:element minOccurs="0" name="last-name" type="xs:string" />
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                            <xs:element name="price" type="xs:decimal" />
                        </xs:sequence>
                        <xs:attribute name="genre" type="xs:string" use="required" />
                        <xs:attribute name="publicationdate" type="xs:date" use="required" />
                        <xs:attribute name="ISBN" type="xs:string" use="required" />
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

다음 코드 예제에서는 XmlReaderSettings 개체의 Schemas 속성에 위 스키마가 추가됩니다. 위 XML 문서의 유효성을 검사하는 XmlReaderSettings 개체의 Create 메서드에 XmlReader 개체가 매개 변수로 전달됩니다.

ValidationType 개체의 XmlReaderSettings 메서드에 의해 XML 문서의 유효성이 검사되도록 Schema 개체의 Create 속성이 XmlReader로 설정됩니다. ValidationEventHandlerXmlReaderSettings 개체에 추가되어 XML 문서와 스키마의 유효성을 검사하는 동안 발견된 오류로 인해 발생한 Warning 또는 Error 이벤트를 처리합니다.

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Schema;

static void booksSettingsValidationEventHandler( Object^ /*sender*/, ValidationEventArgs^ e )
{
   if ( e->Severity == XmlSeverityType::Warning )
   {
      Console::Write( L"WARNING: " );
      Console::WriteLine( e->Message );
   }
   else
   if ( e->Severity == XmlSeverityType::Error )
   {
      Console::Write( L"ERROR: " );
      Console::WriteLine( e->Message );
   }
}

int main()
{
   XmlReaderSettings^ booksSettings = gcnew XmlReaderSettings;
   booksSettings->Schemas->Add( L"http://www.contoso.com/books", L"books.xsd" );
   booksSettings->ValidationType = ValidationType::Schema;
   booksSettings->ValidationEventHandler += gcnew ValidationEventHandler( booksSettingsValidationEventHandler );
   XmlReader^ books = XmlReader::Create( L"books.xml", booksSettings );
   while ( books->Read() )
   {}

   return 0;
}

using System;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaSetExample
{
    static void Main()
    {
        XmlReaderSettings booksSettings = new XmlReaderSettings();
        booksSettings.Schemas.Add("http://www.contoso.com/books", "books.xsd");
        booksSettings.ValidationType = ValidationType.Schema;
        booksSettings.ValidationEventHandler += booksSettingsValidationEventHandler;

        XmlReader books = XmlReader.Create("books.xml", booksSettings);

        while (books.Read()) { }
    }

    static void booksSettingsValidationEventHandler(object sender, ValidationEventArgs e)
    {
        if (e.Severity == XmlSeverityType.Warning)
        {
            Console.Write("WARNING: ");
            Console.WriteLine(e.Message);
        }
        else if (e.Severity == XmlSeverityType.Error)
        {
            Console.Write("ERROR: ");
            Console.WriteLine(e.Message);
        }
    }
}
Imports System.Xml
Imports System.Xml.Schema

Class XmlSchemaSetExample

    Shared Sub Main()

        Dim booksSettings As XmlReaderSettings = New XmlReaderSettings()
        booksSettings.Schemas.Add("http://www.contoso.com/books", "books.xsd")
        booksSettings.ValidationType = ValidationType.Schema
        AddHandler booksSettings.ValidationEventHandler, New ValidationEventHandler(AddressOf booksSettingsValidationEventHandler)

        Dim books As XmlReader = XmlReader.Create("books.xml", booksSettings)

        While books.Read()

        End While

    End Sub

    Shared Sub booksSettingsValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)

        If e.Severity = XmlSeverityType.Warning Then
            Console.Write("WARNING: ")
            Console.WriteLine(e.Message)

        ElseIf e.Severity = XmlSeverityType.Error Then
            Console.Write("ERROR: ")
            Console.WriteLine(e.Message)
        End If

    End Sub

End Class

참고 항목