XmlSchemaSet을 사용하여 유효성 검사

업데이트: November 2007

XmlSchemaSet은 XSD(XML 스키마 정의 언어) 스키마를 저장할 수 있는 캐시 또는 라이브러리입니다. XmlSchemaSet은 파일 또는 URL에서 스키마에 액세스하는 대신 메모리에 있는 스키마를 캐시하여 성능을 향상시킵니다. XmlSchemaSet의 각 스키마는 XmlSchemaSet에 추가될 때 지정한 네임스페이스 URI 및 스키마 위치로 식별됩니다. Schemas 속성은 사용할 XmlSchemaSet 개체를 할당합니다.

예제

다음 예제에서는 XmlSchemaSet에 저장된 스키마를 사용하여 XML 파일의 유효성을 검사합니다. XML 파일의 네임스페이스 urn:bookstore-schema는 XmlSchemaSet에서 유효성 검사에 사용할 스키마를 식별합니다.

Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.IO

public class Sample 

  public shared sub Main() 

    ' Create the XmlSchemaSet class.
    Dim sc as XmlSchemaSet = new XmlSchemaSet()

    ' Add the schema to the collection.
    sc.Add("urn:bookstore-schema", "books.xsd")

    ' Set the validation settings.
    Dim settings as XmlReaderSettings = new XmlReaderSettings()
    settings.ValidationType = ValidationType.Schema
    settings.Schemas = sc
    AddHandler settings.ValidationEventHandler, AddressOf ValidationCallBack

    ' Create the XmlReader object.
    Dim reader as XmlReader = XmlReader.Create("booksSchemaFail.xml", settings)

    ' Parse the file. 
    while reader.Read()
    end while

  end sub

  ' Display any validation errors.
  private shared sub ValidationCallBack(sender as object, e as ValidationEventArgs) 
    Console.WriteLine("Validation Error: {0}", e.Message)
  end sub
end class
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;

public class Sample {

  public static void Main() {

    // Create the XmlSchemaSet class.
    XmlSchemaSet sc = new XmlSchemaSet();

    // Add the schema to the collection.
    sc.Add("urn:bookstore-schema", "books.xsd");

    // Set the validation settings.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas = sc;
    settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);

    // Create the XmlReader object.
    XmlReader reader = XmlReader.Create("booksSchemaFail.xml", settings);

    // Parse the file. 
    while (reader.Read());

  }

  // Display any validation errors.
  private static void ValidationCallBack(object sender, ValidationEventArgs e) {
    Console.WriteLine("Validation Error: {0}", e.Message);
  }
}
#using <System.Xml.dll>

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

// Display any validation errors.
static void ValidationCallBack( Object^ /*sender*/, ValidationEventArgs^ e )
{
   Console::WriteLine( L"Validation Error: {0}", e->Message );
}

int main()
{
   // Create the XmlSchemaSet class.
   XmlSchemaSet^ sc = gcnew XmlSchemaSet;

   // Add the schema to the collection.
   sc->Add( L"urn:bookstore-schema", L"books.xsd" );

   // Set the validation settings.
   XmlReaderSettings^ settings = gcnew XmlReaderSettings;
   settings->ValidationType = ValidationType::Schema;
   settings->Schemas = sc;
   settings->ValidationEventHandler += gcnew ValidationEventHandler( ValidationCallBack );

   // Create the XmlReader object.
   XmlReader^ reader = XmlReader::Create( L"booksSchemaFail.xml", settings );

   // Parse the file. 
   while ( reader->Read() )
      ;

   return 1;
}

입력

이 샘플에서는 다음 두 입력 파일을 사용합니다.

booksSchemaFail.xml

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema">
  <book>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
  </book>
  <book genre="novel">
    <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">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

books.xsd

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">

 <xsd:element name="bookstore" type="bookstoreType"/>

 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="bookType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="authorName"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>

 <xsd:complexType name="authorName">
  <xsd:sequence>
   <xsd:element name="first-name"  type="xsd:string"/>
   <xsd:element name="last-name" type="xsd:string"/>
  </xsd:sequence>
 </xsd:complexType>

</xsd:schema>

출력

유효성 검사 오류: 네임스페이스 'urn:bookstore-schema'의 요소 'book'이 잘못된 자식 요소 'author'를 가지고 있습니다. 'author' 대신 'title'이 필요합니다.

유효성 검사 오류: 네임스페이스 'urn:bookstore-schema'의 요소 'author'가 잘못된 자식 요소 'name'을 가지고 있습니다. 'name' 대신 'first-name'이 필요합니다.

참고 항목

개념

XmlReader로 XML 읽기

기타 리소스

XmlReader를 사용하여 XML 데이터의 유효성 검사