다음을 통해 공유


래핑된 XmlReader 개체를 사용하여 유효성 검사

업데이트: November 2007

다른 XmlReader 개체 주위에 래핑된 새 XmlReader 개체를 만들 수 있습니다. 그런 다음 다른 XmlReader 개체 위에 기능을 추가할 수 있습니다. 예를 들어, XmlNodeReader 클래스는 데이터 유효성 검사를 지원하지 않습니다. XmlNodeReader 개체 주위를 래핑하는 XmlReader 개체를 만들면 XmlNodeReader 개체에 저장된 데이터의 유효성을 검사할 수 있습니다.

예제

다음 예제에서는 XML 파일을 XML 문서에 로드한 후 수정합니다. XML 문서가 XmlNodeReader에 전달되고 나서 이 개체가 XmlReader.Create 메서드에 전달됩니다. 유효성 검사 판독기에서 파일을 구문 분석할 때 XML 파일의 변경 내용에 대해 유효성을 검사할 수 있습니다.

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

public class Sample 

  public shared sub Main() 

    ' Create and load the XML document.
    Dim doc as XmlDocument = new XmlDocument()
    doc.Load("booksSchema.xml")

    ' Make changes to the document.
    Dim book as XmlElement
    book = CType(doc.DocumentElement.FirstChild, XmlElement)
    book.SetAttribute("publisher", "Worldwide Publishing")

    ' Create an XmlNodeReader using the XML document.
    Dim nodeReader as XmlNodeReader = new XmlNodeReader(doc)

    ' Set the validation settings on the XmlReaderSettings object.
    Dim settings as XmlReaderSettings = new XmlReaderSettings()
    settings.ValidationType = ValidationType.Schema
    settings.Schemas.Add("urn:bookstore-schema", "books.xsd")
    AddHandler settings.ValidationEventHandler, AddressOf ValidationCallBack

    ' Create a validating reader that wraps the XmlNodeReader object.
    Dim reader as XmlReader = XmlReader.Create(nodeReader,settings)

    ' Parse the XML 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 and load the XML document.
    XmlDocument doc = new XmlDocument();
    doc.Load("booksSchema.xml");

    // Make changes to the document.
    XmlElement book = (XmlElement) doc.DocumentElement.FirstChild;
    book.SetAttribute("publisher", "Worldwide Publishing");

    // Create an XmlNodeReader using the XML document.
    XmlNodeReader nodeReader = new XmlNodeReader(doc);

    // Set the validation settings on the XmlReaderSettings object.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add("urn:bookstore-schema", "books.xsd");
    settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);

   // Create a validating reader that wraps the XmlNodeReader object.
   XmlReader reader = XmlReader.Create(nodeReader, settings);

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

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

입력

다음 파일이 입력으로 사용됩니다.

bookSchema.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>

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>

출력

유효성 검사 오류: 'publisher' 특성이 선언되지 않았습니다.

참고 항목

개념

XmlReader로 XML 읽기

기타 리소스

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