다음을 통해 공유


XmlValidatingReader.Schemas 속성

유효성 검사에 사용할 XmlSchemaCollection입니다.

네임스페이스: System.Xml
어셈블리: System.Xml(system.xml.dll)

구문

‘선언
Public ReadOnly Property Schemas As XmlSchemaCollection
‘사용 방법
Dim instance As XmlValidatingReader
Dim value As XmlSchemaCollection

value = instance.Schemas
public XmlSchemaCollection Schemas { get; }
public:
property XmlSchemaCollection^ Schemas {
    XmlSchemaCollection^ get ();
}
/** @property */
public XmlSchemaCollection get_Schemas ()
public function get Schemas () : XmlSchemaCollection

속성 값

유효성 검사에 사용할 XmlSchemaCollection입니다.

설명

참고

XmlValidatingReader 클래스는 Microsoft .NET Framework version 2.0에서 사용되지 않습니다. XmlReaderSettings 클래스와 Create 메서드를 사용하여 유효성 검사 XmlReader 인스턴스를 만들 수 있습니다. 자세한 내용은 XmlReader를 사용하여 XML 데이터의 유효성 검사를 참조하십시오.

XmlSchemaCollection은 미리 로드된 XDR(XML-Data Reduced) 및 XSD(XML 스키마 정의 언어) 스키마를 보유합니다. 이 속성을 통해 판독기는 스키마의 캐시에 액세스할 수 있으며 매 번 스키마를 다시 로드하지 않고 유효성을 검사할 수 있습니다. 판독기는 XmlSchemaCollection에 아무 것도 추가하지 않습니다.

XmlSchemaCollection에 다른 네임스페이스를 참조하는 include 또는 import 요소를 포함하는 XML 스키마(XSD)가 있으면 다른 네임스페이스에 대한 스키마는 유효성 검사를 목적으로만 로드됩니다. 이러한 스키마가 명시적으로 스키마 컬렉션에 추가되지 않으면 컬렉션 메서드나 속성을 사용하여 액세스할 수 없습니다. 예들 들어, 스키마 파일 b.xsd에 대한 참조를 포함하는 스키마 파일 a.xsd가 컬렉션에 있는 경우 스키마 컬렉션에 b.xsd를 추가해야 컬렉션 메서드나 속성을 사용하여 액세스할 수 있습니다.

Schemas 속성을 사용하여 XmlSchemaCollection에 액세스하는 경우, XmlSchemaCollection.Add 메서드는 XmlValidatingReader.XmlResolver 속성으로 지정된 XmlResolver를 사용합니다.

참고

Read를 처음으로 호출하기 전에 XmlSchemaCollection에 스키마를 추가해야 합니다.

자세한 내용은 XmlValidatingReader를 사용하여 XML의 유효성 검사를 참조하십시오.

예제

다음 예제에서는 XmlSchemaCollection에 저장된 스키마를 사용하여 세 가지 XML 파일의 유효성을 검사합니다.

Option Strict
Option Explicit

Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.Schema
Imports Microsoft.VisualBasic

Public Class SchemaCollectionSample
    Private doc1 As String = "booksSchema.xml"
    Private doc2 As String = "booksSchemaFail.xml"
    Private doc3 As String = "newbooks.xml"
    Private schema As String = "books.xsd"
    Private schema1 As String = "schema1.xdr"
    
    Private reader As XmlTextReader = Nothing
    Private vreader As XmlValidatingReader = Nothing
    Private m_success As Boolean = True
    
    Public Sub New()

            'Load the schema collection
            Dim xsc As New XmlSchemaCollection()
            xsc.Add("urn:bookstore-schema", schema) 'XSD schema
            xsc.Add("urn:newbooks-schema", schema1) 'XDR schema

            'Validate the files using schemas stored in the collection.
            Validate(doc1, xsc) 'Should pass.
            Validate(doc2, xsc) 'Should fail.   
            Validate(doc3, xsc) 'Should fail. 
        
    End Sub 'New
    
    Public Shared Sub Main()
        Dim validation As New SchemaCollectionSample()
    End Sub 'Main
    
    Private Sub Validate(filename As String, xsc As XmlSchemaCollection)
        
            m_success = True
            Console.WriteLine()
            Console.WriteLine("Validating XML file {0}...", filename.ToString())
            reader = New XmlTextReader(filename)
            
            'Create a validating reader.
            vreader = New XmlValidatingReader(reader)
            
            'Use the schemas stored in the schema collection.
            vreader.Schemas.Add(xsc)
            
            'Set the validation event handler.
            AddHandler vreader.ValidationEventHandler, AddressOf ValidationCallBack
            'Read and validate the XML data.
            While vreader.Read()
            End While
            Console.WriteLine("Validation finished. Validation {0}", IIf(m_success, "successful", "failed"))
            Console.WriteLine()

            'Close the reader.
            vreader.Close()

    End Sub 'Validate
       
    
    Private Sub ValidationCallBack(sender As Object, args As ValidationEventArgs)
        m_success = False
        
        Console.Write((ControlChars.CrLf & ControlChars.Tab & "Validation error: " & args.Message))
    End Sub 'ValidationCallBack 
End Class 'SchemaCollectionSample
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class SchemaCollectionSample
{
  private const String doc1 = "booksSchema.xml";
  private const String doc2 = "booksSchemaFail.xml";
  private const String doc3 = "newbooks.xml";
  private const String schema = "books.xsd";
  private const String schema1 = "schema1.xdr";
  
  private XmlTextReader reader=null;
  private XmlValidatingReader vreader = null;
  private Boolean m_success = true;

  public SchemaCollectionSample ()
  {
    //Load the schema collection.
    XmlSchemaCollection xsc = new XmlSchemaCollection();
    xsc.Add("urn:bookstore-schema", schema);  //XSD schema
    xsc.Add("urn:newbooks-schema", schema1);  //XDR schema

    //Validate the files using schemas stored in the collection.
    Validate(doc1, xsc); //Should pass.
    Validate(doc2, xsc); //Should fail.   
    Validate(doc3, xsc); //Should fail. 

  }    

  public static void Main ()
  {
      SchemaCollectionSample validation = new SchemaCollectionSample();
  }

  private void Validate(String filename, XmlSchemaCollection xsc)
  {
   
     m_success = true;
     Console.WriteLine();
     Console.WriteLine("Validating XML file {0}...", filename.ToString());
     reader = new XmlTextReader (filename);
        
     //Create a validating reader.
    vreader = new XmlValidatingReader (reader);

     //Validate using the schemas stored in the schema collection.
     vreader.Schemas.Add(xsc);
 
     //Set the validation event handler
     vreader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
     //Read and validate the XML data.
     while (vreader.Read()){}
     Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful" : "failed"));
     Console.WriteLine();

     //Close the reader.
     vreader.Close();

  } 


  private void ValidationCallBack (object sender, ValidationEventArgs args)
  {
     m_success = false;

     Console.Write("\r\n\tValidation error: " + args.Message);

  }  
}
#using <System.dll>
#using <System.Xml.dll>

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

public ref class SchemaCollectionSample
{
private:
   XmlTextReader^ reader;
   XmlValidatingReader^ vreader;
   Boolean m_success;

public:
   SchemaCollectionSample()
   {
      reader = nullptr;
      vreader = nullptr;
      m_success = true;

      //Load the schema collection.
      XmlSchemaCollection^ xsc = gcnew XmlSchemaCollection;
      String^ schema = "books.xsd";
      String^ schema1 = "schema1.xdr";
      xsc->Add( "urn:bookstore-schema", schema ); //XSD schema
      xsc->Add( "urn:newbooks-schema", schema1 ); //XDR schema
      String^ doc1 = "booksSchema.xml";
      String^ doc2 = "booksSchemaFail.xml";
      String^ doc3 = "newbooks.xml";

      //Validate the files using schemas stored in the collection.
      Validate( doc1, xsc ); //Should pass.
      Validate( doc2, xsc ); //Should fail.   
      Validate( doc3, xsc ); //Should fail. 
   }


private:
   void Validate( String^ filename, XmlSchemaCollection^ xsc )
   {
      m_success = true;
      Console::WriteLine();
      Console::WriteLine( "Validating XML file {0}...", filename );
      reader = gcnew XmlTextReader( filename );

      //Create a validating reader.
      vreader = gcnew XmlValidatingReader( reader );

      //Validate using the schemas stored in the schema collection.
      vreader->Schemas->Add( xsc );

      //Set the validation event handler
      vreader->ValidationEventHandler += gcnew ValidationEventHandler( this, &SchemaCollectionSample::ValidationCallBack );

      //Read and validate the XML data.
      while ( vreader->Read() )
      {}

      Console::WriteLine( "Validation finished. Validation {0}", (m_success == true ? (String^)"successful" : "failed") );
      Console::WriteLine();

      //Close the reader.
      vreader->Close();
   }

   void ValidationCallBack( Object^ /*sender*/, ValidationEventArgs^ args )
   {
      m_success = false;
      Console::Write( "\r\n\tValidation error: {0}", args->Message );
   }

};

int main()
{
   gcnew SchemaCollectionSample;
}
import System.*;
import System.IO.*;
import System.Xml.*;
import System.Xml.Schema.*;

public class SchemaCollectionSample
{
    private String doc1 = "booksSchema.xml";
    private String doc2 = "booksSchemaFail.xml";
    private String doc3 = "newbooks.xml";
    private String schema = "books.xsd";
    private String schema1 = "schema1.xdr";
    private XmlTextReader reader = null;
    private XmlValidatingReader vReader = null;
    private boolean mSuccess = true;

    public SchemaCollectionSample() 
    {
        //Load the schema collection.
        XmlSchemaCollection xsc =  new XmlSchemaCollection();
        xsc.Add("urn:bookstore-schema", schema); //XSD schema
        xsc.Add("urn:newbooks-schema", schema1); //XDR schema

        //Validate the files using schemas stored in the collection.
        Validate(doc1, xsc); //Should pass.
        Validate(doc2, xsc); //Should fail.   
        Validate(doc3, xsc); //Should fail. 
    } //SchemaCollectionSample
    
    public static void main(String[] args)
    {
        SchemaCollectionSample validation = new SchemaCollectionSample();
    } //main

    private void Validate(String filename, XmlSchemaCollection xsc) 
    {
        mSuccess = true;
        Console.WriteLine();
        Console.WriteLine("Validating XML file {0}...", filename.ToString());
        reader = new XmlTextReader(filename);

        //Create a validating reader.
        vReader = new XmlValidatingReader(reader);

        //Validate using the schemas stored in the schema collection.
        vReader.get_Schemas().Add(xsc);

        //Set the validation event handler
        vReader.add_ValidationEventHandler
            (new ValidationEventHandler(ValidationCallBack));

        //Read and validate the XML data.
        while(vReader.Read()) {

        }
        Console.WriteLine("Validation finished. Validation {0}",
            (mSuccess == true) ? "successful" : "failed");
        Console.WriteLine();

        //Close the reader.
        vReader.Close();
    } //Validate

    private void ValidationCallBack(Object sender, ValidationEventArgs args)
    {
        mSuccess = false;
        Console.Write(("\r\n\tValidation error: " + args.get_Message()));
    } //ValidationCallBack 
} //SchemaCollectionSample

샘플은 다음과 같은 다섯 개의 입력 파일을 사용합니다.

booksSchema.xml

<?xml version='1.0'?>
 <bookstore xmlns="urn:bookstore-schema">
   <book genre="autobiography">
     <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">
     <title>The Confidence Man</title>
     <author>
       <first-name>Herman</first-name>
       <last-name>Melville</last-name>
     </author>
     <price>11.99</price>
   </book>
 </bookstore>

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>

newbooks.xml

<?xml version='1.0'?>
<bookstore xmlns="urn:newbooks-schema">
  <book genre="novel" style="hardcover">
    <title>The Handmaid's Tale</title>
    <author>
      <first-name>Margaret</first-name>
      <last-name>Atwood</last-name>
    </author>
    <price>19.95</price>
  </book>
  <book genre="novel" style="other">
    <title>The Poisonwood Bible</title>
    <author>
      <first-name>Barbara</first-name>
      <last-name>Kingsolver</last-name>
    </author>
    <price>11.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>

schema1.xdr

<?xml version="1.0"?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data"
        xmlns:dt="urn:schemas-microsoft-com:datatypes">
  <ElementType name="first-name" content="textOnly"/>
  <ElementType name="last-name" content="textOnly"/>
  <ElementType name="name" content="textOnly"/>
  <ElementType name="price" content="textOnly" dt:type="fixed.14.4"/>
  <ElementType name="author" content="eltOnly" order="one">
    <group order="seq">
      <element type="name"/>
    </group>
    <group order="seq">
      <element type="first-name"/>
      <element type="last-name"/>
    </group>
  </ElementType>
  <ElementType name="title" content="textOnly"/>
  <AttributeType name="genre" dt:type="string"/>
  <AttributeType name="style" dt:type="enumeration"
        dt:values="paperback hardcover"/>
  <ElementType name="book" content="eltOnly">
    <attribute type="genre" required="yes"/>
    <attribute type="style" required="yes"/>
    <element type="title"/>
    <element type="author"/>
    <element type="price"/>
  </ElementType>
  <ElementType name="bookstore" content="eltOnly">
    <element type="book"/>
  </ElementType>
</Schema>

플랫폼

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

참고 항목

참조

XmlValidatingReader 클래스
XmlValidatingReader 멤버
System.Xml 네임스페이스

기타 리소스

XmlReader로 XML 읽기