System.Xml.Schema.XmlSchemaSet 클래스

이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.

Important

  • 알 수 없거나 신뢰할 수 없는 원본 또는 위치의 스키마를 사용하지 마세요. 이렇게 하면 코드의 보안이 손상됩니다.
  • XML 스키마(인라인 스키마 포함)는 기본적으로 서비스 거부 공격에 취약합니다. 신뢰할 수 없는 시나리오에서는 허용하지 않습니다.
  • 스키마 유효성 검사 오류 메시지 및 예외는 스키마 파일에 대한 con텐트 모드l 또는 URI 경로에 대한 중요한 정보를 노출할 수 있습니다. 신뢰할 수 없는 호출자에게 이 정보를 노출하지 않도록 주의하세요.
  • 추가 보안 고려 사항은 "보안 고려 사항" 섹션에서 다룹니다.

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

보안 고려 사항

  • 알 수 없거나 신뢰할 수 없는 원본의 스키마를 사용하지 마세요. 이렇게 하면 코드의 보안이 손상됩니다. 스키마의 포함, 가져오기 및 재정의 요소에서 참조되는 외부 네임스페이스 또는 위치는 스키마를 포함하거나 가져오는 스키마의 기본 URI와 관련하여 확인됩니다. 예를 들어 포함 또는 가져오기 스키마의 기본 URI가 비어 있거나 null현재 디렉터리와 관련하여 외부 위치가 확인됩니다. 클래스는 XmlUrlResolver 기본적으로 외부 스키마를 확인하는 데 사용됩니다. 스키마의 포함, 가져오기 및 다시 정의 요소의 확인을 사용하지 않도록 설정하려면 속성을 null.로 설정합니다XmlSchemaSet.XmlResolver.

  • 클래스는 XmlSchemaSet 클래스를 System.Text.RegularExpressions.Regex 사용하여 XML 스키마의 정규식을 구문 분석하고 일치합니다. XML 스키마에서 정규식을 사용하는 패턴 패싯의 유효성 검사에는 CPU 사용량이 증가할 수 있으며 고가용성 시나리오에서는 피해야 합니다.

  • 클래스를 사용한 XmlSchemaSet 결과로 발생한 예외(예: XmlSchemaException 클래스)는 신뢰할 수 없는 시나리오에서 노출되어서는 안 되는 중요한 정보를 포함할 수 있습니다. 예를 들어 속성은 SourceUriXmlSchemaException 예외를 발생시킨 스키마 파일에 대한 URI 경로를 반환합니다. 신뢰할 SourceUri 수 없는 시나리오에서는 속성을 노출해서는 안 됩니다. 이 중요한 정보가 신뢰할 수 없는 시나리오에서 노출되지 않도록 예외를 올바르게 처리해야 합니다.

예제

다음 예제에서는 에 저장된 스키마를 사용하여 XML 파일의 유효성을 XmlSchemaSet검사합니다. XML 파일 urn:bookstore-schema의 네임스페이스는 유효성 검사에 XmlSchemaSet 사용할 스키마를 식별합니다. 예제의 출력은 XML 파일에 두 가지 스키마 위반이 있음을 보여 줍니다.

  • 첫 번째 <책> 요소에는 작성>자 <요소가 포함되지만 제목>이나 <가격> 요소는 없습니다<.

  • 마지막 책 요소의 author> 요소에 이름> 및 <성> 요소가 없<으므로 대신 잘못된 <이름> 요소가 있습니다.><<

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 += 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:\n   {e.Message}\n");
  }
}
// The example displays output like the following:
//   Validation Error:
//        The element 'book' in namespace 'urn:bookstore-schema' has invalid child element 'author'
//        in namespace 'urn:bookstore-schema'. List of possible elements expected: 'title' in
//        namespace 'urn:bookstore-schema'.
//
//    Validation Error:
//       The element 'author' in namespace 'urn:bookstore-schema' has invalid child element 'name'
//       in namespace 'urn:bookstore-schema'. List of possible elements expected: 'first-name' in
//       namespace 'urn:bookstore-schema'.
Imports System.Xml
Imports System.Xml.Schema
Imports System.IO

Public Module Sample 
  Public 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 Sub ValidationCallBack(sender as object, e as ValidationEventArgs) 
    Console.WriteLine($"Validation Error:{vbCrLf}   {e.Message}")
    Console.WriteLine()
  End Sub
End Module
' The example displays output like the following:
'   Validation Error: 
'        The element 'book' in namespace 'urn:bookstore-schema' has invalid child element 'author' 
'        in namespace 'urn:bookstore-schema'. List of possible elements expected: 'title' in 
'        namespace 'urn:bookstore-schema'.
'
'    Validation Error: 
'       The element 'author' in namespace 'urn:bookstore-schema' has invalid child element 'name' 
'       in namespace 'urn:bookstore-schema'. List of possible elements expected: 'first-name' in 
'       namespace 'urn:bookstore-schema'.

입력

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

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>