XmlSchemaValidator 클래스는 푸시 기반 방식으로 XML 스키마에 대해 XML 데이터의 유효성을 검사하는 효율적이고 고성능 메커니즘을 제공합니다. 예를 들어 XmlSchemaValidator 클래스를 사용하면 XML 문서로 직렬화하거나 유효성 검사 XML 판독기로 다시 분석할 필요 없이 XML 정보 세트의 유효성을 바로 검사할 수 있습니다.
XmlSchemaValidator 클래스는 사용자 지정 XML 데이터 원본을 통해 유효성 검사 엔진을 빌드하거나 유효성 검사 XML 기록기를 빌드하는 방법으로 고급 시나리오에서 사용할 수 있습니다.
다음은 XmlSchemaValidator 클래스를 사용하여 contosoBooks.xml
스키마에 대해 contosoBooks.xsd
파일의 유효성을 검사하는 예제입니다. 이 예제에서는 XmlSerializer 클래스를 사용하여 contosoBooks.xml
파일을 역직렬화하고 노드 값을 XmlSchemaValidator 클래스의 메서드에 전달합니다.
비고
이 예제는 이 항목의 섹션 전체에서 사용됩니다.
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Collections;
namespace Microsoft.Samples.Xml.Schema
{
class XmlSchemaValidatorExamples
{
static void Main()
{
// The XML document to deserialize into the XmlSerializer object.
XmlReader reader = XmlReader.Create("contosoBooks.xml");
// The XmlSerializer object.
XmlSerializer serializer = new XmlSerializer(typeof(ContosoBooks));
ContosoBooks books = (ContosoBooks)serializer.Deserialize(reader);
// The XmlSchemaSet object containing the schema used to validate the XML document.
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add("http://www.contoso.com/books", "contosoBooks.xsd");
// The XmlNamespaceManager object used to handle namespaces.
XmlNamespaceManager manager = new XmlNamespaceManager(reader.NameTable);
// Assign a ValidationEventHandler to handle schema validation warnings and errors.
XmlSchemaValidator validator = new XmlSchemaValidator(reader.NameTable, schemaSet, manager, XmlSchemaValidationFlags.None);
validator.ValidationEventHandler += new ValidationEventHandler(SchemaValidationEventHandler);
// Initialize the XmlSchemaValidator object.
validator.Initialize();
// Validate the bookstore element, verify that all required attributes are present
// and prepare to validate child content.
validator.ValidateElement("bookstore", "http://www.contoso.com/books", null);
validator.GetUnspecifiedDefaultAttributes(new ArrayList());
validator.ValidateEndOfAttributes(null);
// Get the next expected element in the bookstore context.
XmlSchemaParticle[] particles = validator.GetExpectedParticles();
XmlSchemaElement nextElement = particles[0] as XmlSchemaElement;
Console.WriteLine($"Expected Element: '{nextElement.Name}'");
foreach (BookType book in books.Book)
{
// Validate the book element.
validator.ValidateElement("book", "http://www.contoso.com/books", null);
// Get the expected attributes for the book element.
Console.Write("\nExpected attributes: ");
XmlSchemaAttribute[] attributes = validator.GetExpectedAttributes();
foreach (XmlSchemaAttribute attribute in attributes)
{
Console.Write("'{0}' ", attribute.Name);
}
Console.WriteLine();
// Validate the genre attribute and display its post schema validation information.
if (book.Genre != null)
{
validator.ValidateAttribute("genre", "", book.Genre, schemaInfo);
}
DisplaySchemaInfo();
// Validate the publicationdate attribute and display its post schema validation information.
if (book.PublicationDate != null)
{
validator.ValidateAttribute("publicationdate", "", dateTimeGetter(book.PublicationDate), schemaInfo);
}
DisplaySchemaInfo();
// Validate the ISBN attribute and display its post schema validation information.
if (book.Isbn != null)
{
validator.ValidateAttribute("ISBN", "", book.Isbn, schemaInfo);
}
DisplaySchemaInfo();
// After validating all the attributes for the current element with ValidateAttribute method,
// you must call GetUnspecifiedDefaultAttributes to validate the default attributes.
validator.GetUnspecifiedDefaultAttributes(new ArrayList());
// Verify that all required attributes of the book element are present
// and prepare to validate child content.
validator.ValidateEndOfAttributes(null);
// Validate the title element and its content.
validator.ValidateElement("title", "http://www.contoso.com/books", null);
validator.ValidateEndElement(null, book.Title);
// Validate the author element, verify that all required attributes are present
// and prepare to validate child content.
validator.ValidateElement("author", "http://www.contoso.com/books", null);
validator.GetUnspecifiedDefaultAttributes(new ArrayList());
validator.ValidateEndOfAttributes(null);
if (book.Author.Name != null)
{
// Validate the name element and its content.
validator.ValidateElement("name", "http://www.contoso.com/books", null);
validator.ValidateEndElement(null, book.Author.Name);
}
if (book.Author.FirstName != null)
{
// Validate the first-name element and its content.
validator.ValidateElement("first-name", "http://www.contoso.com/books", null);
validator.ValidateEndElement(null, book.Author.FirstName);
}
if (book.Author.LastName != null)
{
// Validate the last-name element and its content.
validator.ValidateElement("last-name", "http://www.contoso.com/books", null);
validator.ValidateEndElement(null, book.Author.LastName);
}
// Validate the content of the author element.
validator.ValidateEndElement(null);
// Validate the price element and its content.
validator.ValidateElement("price", "http://www.contoso.com/books", null);
validator.ValidateEndElement(null, book.Price);
// Validate the content of the book element.
validator.ValidateEndElement(null);
}
// Validate the content of the bookstore element.
validator.ValidateEndElement(null);
// Close the XmlReader object.
reader.Close();
}
static XmlSchemaInfo schemaInfo = new XmlSchemaInfo();
static object dateTimeGetterContent;
static object dateTimeGetterHandle()
{
return dateTimeGetterContent;
}
static XmlValueGetter dateTimeGetter(DateTime dateTime)
{
dateTimeGetterContent = dateTime;
return new XmlValueGetter(dateTimeGetterHandle);
}
static void DisplaySchemaInfo()
{
if (schemaInfo.SchemaElement != null)
{
Console.WriteLine($"Element '{schemaInfo.SchemaElement.Name}' with type '{schemaInfo.SchemaType}' is '{schemaInfo.Validity}'");
}
else if (schemaInfo.SchemaAttribute != null)
{
Console.WriteLine($"Attribute '{schemaInfo.SchemaAttribute.Name}' with type '{schemaInfo.SchemaType}' is '{schemaInfo.Validity}'");
}
}
static void SchemaValidationEventHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
Console.WriteLine($"\nError: {e.Message}");
break;
case XmlSeverityType.Warning:
Console.WriteLine($"\nWarning: {e.Message}");
break;
}
}
}
[XmlRootAttribute("bookstore", Namespace = "http://www.contoso.com/books", IsNullable = false)]
public class ContosoBooks
{
[XmlElementAttribute("book")]
public BookType[] Book;
}
public class BookType
{
[XmlAttributeAttribute("genre")]
public string Genre;
[XmlAttributeAttribute("publicationdate", DataType = "date")]
public DateTime PublicationDate;
[XmlAttributeAttribute("ISBN")]
public string Isbn;
[XmlElementAttribute("title")]
public string Title;
[XmlElementAttribute("author")]
public BookAuthor Author;
[XmlElementAttribute("price")]
public Decimal Price;
}
public class BookAuthor
{
[XmlElementAttribute("name")]
public string Name;
[XmlElementAttribute("first-name")]
public string FirstName;
[XmlElementAttribute("last-name")]
public string LastName;
}
}
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.Serialization
Imports System.Collections
Namespace Microsoft.Samples.Xml.Schema
Class XmlSchemaValidatorExamples
Shared Sub Main()
' The XML document to deserialize into the XmlSerializer object.
Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml")
' The XmlSerializer object.
Dim serializer As XmlSerializer = New XmlSerializer(GetType(ContosoBooks))
Dim books As ContosoBooks = CType(serializer.Deserialize(reader), ContosoBooks)
' The XmlSchemaSet object containing the schema used to validate the XML document.
Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
schemaSet.Add("http://www.contoso.com/books", "contosoBooks.xsd")
' The XmlNamespaceManager object used to handle namespaces.
Dim manager As XmlNamespaceManager = New XmlNamespaceManager(reader.NameTable)
' Assign a ValidationEventHandler to handle schema validation warnings and errors.
Dim validator As XmlSchemaValidator = New XmlSchemaValidator(reader.NameTable, schemaSet, manager, XmlSchemaValidationFlags.None)
'validator.ValidationEventHandler += New ValidationEventHandler(SchemaValidationEventHandler)
AddHandler validator.ValidationEventHandler, AddressOf SchemaValidationEventHandler
' Initialize the XmlSchemaValidator object.
validator.Initialize()
' Validate the bookstore element, verify that all required attributes are present
' and prepare to validate child content.
validator.ValidateElement("bookstore", "http://www.contoso.com/books", Nothing)
validator.GetUnspecifiedDefaultAttributes(New ArrayList())
validator.ValidateEndOfAttributes(Nothing)
' Get the next expected element in the bookstore context.
Dim particles() As XmlSchemaParticle = validator.GetExpectedParticles()
Dim nextElement As XmlSchemaElement = particles(0)
Console.WriteLine("Expected Element: '{0}'", nextElement.Name)
For Each book As BookType In books.book
' Validate the book element.
validator.ValidateElement("book", "http://www.contoso.com/books", Nothing)
' Get the expected attributes for the book element.
Console.Write(vbCrLf & "Expected attributes: ")
Dim attributes() As XmlSchemaAttribute = validator.GetExpectedAttributes()
For Each attribute As XmlSchemaAttribute In attributes
Console.Write("'{0}' ", attribute.Name)
Next
Console.WriteLine()
' Validate the genre attribute and display its post schema validation information.
If Not book.Genre Is Nothing Then
validator.ValidateAttribute("genre", "", book.Genre, schemaInfo)
End If
DisplaySchemaInfo()
' Validate the publicationdate attribute and display its post schema validation information.
If Not book.PublicationDate = Nothing Then
validator.ValidateAttribute("publicationdate", "", dateTimeGetter(book.PublicationDate), schemaInfo)
End If
DisplaySchemaInfo()
' Validate the ISBN attribute and display its post schema validation information.
If Not book.Isbn Is Nothing Then
validator.ValidateAttribute("ISBN", "", book.Isbn, schemaInfo)
End If
DisplaySchemaInfo()
' After validating all the attributes for the current element with ValidateAttribute method,
' you must call GetUnspecifiedDefaultAttributes to validate the default attributes.
validator.GetUnspecifiedDefaultAttributes(New ArrayList())
' Verify that all required attributes of the book element are present
' and prepare to validate child content.
validator.ValidateEndOfAttributes(Nothing)
' Validate the title element and its content.
validator.ValidateElement("title", "http://www.contoso.com/books", Nothing)
validator.ValidateEndElement(Nothing, book.Title)
' Validate the author element, verify that all required attributes are present
' and prepare to validate child content.
validator.ValidateElement("author", "http://www.contoso.com/books", Nothing)
validator.GetUnspecifiedDefaultAttributes(New ArrayList())
validator.ValidateEndOfAttributes(Nothing)
If Not book.Author.Name Is Nothing Then
' Validate the name element and its content.
validator.ValidateElement("name", "http://www.contoso.com/books", Nothing)
validator.ValidateEndElement(Nothing, book.Author.Name)
End If
If Not book.Author.FirstName Is Nothing Then
' Validate the first-name element and its content.
validator.ValidateElement("first-name", "http://www.contoso.com/books", Nothing)
validator.ValidateEndElement(Nothing, book.Author.FirstName)
End If
If Not book.Author.LastName Is Nothing Then
' Validate the last-name element and its content.
validator.ValidateElement("last-name", "http://www.contoso.com/books", Nothing)
validator.ValidateEndElement(Nothing, book.Author.LastName)
End If
' Validate the content of the author element.
validator.ValidateEndElement(Nothing)
' Validate the price element and its content.
validator.ValidateElement("price", "http://www.contoso.com/books", Nothing)
validator.ValidateEndElement(Nothing, book.Price)
' Validate the content of the book element.
validator.ValidateEndElement(Nothing)
Next
' Validate the content of the bookstore element.
validator.ValidateEndElement(Nothing)
' Close the XmlReader object.
reader.Close()
End Sub
Shared schemaInfo As XmlSchemaInfo = New XmlSchemaInfo()
Shared dateTimeGetterContent As Object
Shared Function dateTimeGetterHandle() As Object
Return dateTimeGetterContent
End Function
Shared Function dateTimeGetter(ByVal dateTime As DateTime) As XmlValueGetter
dateTimeGetterContent = dateTime
Return New XmlValueGetter(AddressOf dateTimeGetterHandle)
End Function
Shared Sub DisplaySchemaInfo()
If Not schemaInfo.SchemaElement Is Nothing Then
Console.WriteLine("Element '{0}' with type '{1}' is '{2}'", schemaInfo.SchemaElement.Name, schemaInfo.SchemaType, schemaInfo.Validity)
ElseIf Not schemaInfo.SchemaAttribute Is Nothing Then
Console.WriteLine("Attribute '{0}' with type '{1}' is '{2}'", schemaInfo.SchemaAttribute.Name, schemaInfo.SchemaType, schemaInfo.Validity)
End If
End Sub
Shared Sub SchemaValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
Select Case e.Severity
Case XmlSeverityType.Error
Console.WriteLine(vbCrLf & "Error: {0}", e.Message)
Exit Sub
Case XmlSeverityType.Warning
Console.WriteLine(vbCrLf & "Warning: {0}", e.Message)
Exit Sub
End Select
End Sub
End Class
<XmlRootAttribute("bookstore", Namespace:="http://www.contoso.com/books", IsNullable:=False)> _
Public Class ContosoBooks
<XmlElementAttribute("book")> _
Public book() As BookType
End Class
Public Class BookType
<XmlAttributeAttribute("genre")> _
Public Genre As String
<XmlAttributeAttribute("publicationdate", DataType:="date")> _
Public PublicationDate As DateTime
<XmlAttributeAttribute("ISBN")> _
Public Isbn As String
<XmlElementAttribute("title")> _
Public Title As String
<XmlElementAttribute("author")> _
Public Author As BookAuthor
<XmlElementAttribute("price")> _
Public Price As Decimal
End Class
Public Class BookAuthor
<XmlElementAttribute("name")> _
Public Name As String
<XmlElementAttribute("first-name")> _
Public FirstName As String
<XmlElementAttribute("last-name")> _
Public LastName As String
End Class
End Namespace
이 예제에서는 contosoBooks.xml
파일을 입력으로 사용합니다.
<?xml version="1.0" encoding="utf-8" ?>
<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>
또한 이 예제에서는 contosoBooks.xsd
입력으로 사용합니다.
<?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>
XmlSchemaValidator를 사용하여 XML 데이터 유효성 검사
XML 정보 세트의 유효성 검사를 시작하려면 먼저 XmlSchemaValidator 생성자를 사용하여 XmlSchemaValidator 클래스의 새 인스턴스를 초기화해야 합니다.
XmlSchemaValidator 생성자는 XmlNameTable, XmlSchemaSet, 및 XmlNamespaceManager 객체와 XmlSchemaValidationFlags 값을 매개변수로 받습니다. XmlNameTable 개체는 스키마 네임스페이스, XML 네임스페이스 등과 같이 잘 알려진 네임스페이스 문자열을 원자화하는 데 사용되며 간단한 콘텐츠의 유효성을 검사하는 동안 ParseValue 메서드에 전달됩니다. XmlSchemaSet 개체에는 XML 정보 세트의 유효성을 검사하는 데 사용되는 XML 스키마가 포함되어 있습니다. XmlNamespaceManager 개체는 유효성 검사 중에 발생한 네임스페이스를 확인하는 데 사용됩니다. XmlSchemaValidationFlags 값은 유효성 검사의 특정 기능을 사용하지 않도록 설정하는 데 사용됩니다.
XmlSchemaValidator 생성자에 대한 자세한 내용은 XmlSchemaValidator 클래스 참조 설명서를 참조하세요.
유효성 검사 초기화
XmlSchemaValidator 개체가 생성된 후에는 Initialize 개체의 상태를 초기화하는 데 사용되는 두 가지 오버로드된 XmlSchemaValidator 메서드가 있습니다. 다음은 두 가지 Initialize 메서드입니다.
기본 XmlSchemaValidator.Initialize 메서드는 XmlSchemaValidator 개체를 시작 상태로 초기화하고 매개 변수로 XmlSchemaValidator.Initialize 사용하는 오버로드된 XmlSchemaObject 메서드는 부분 유효성 검사를 위해 XmlSchemaValidator 개체를 시작 상태로 초기화합니다.
두 Initialize 메서드는 XmlSchemaValidator 개체를 생성한 직후 또는 EndValidation호출한 후에만 호출할 수 있습니다.
XmlSchemaValidator.Initialize 메서드의 예제는 소개의 예제를 참조하세요. Initialize 메서드에 대한 자세한 내용은 XmlSchemaValidator 클래스 참조 설명서를 참조하세요.
부분 유효성 검사
XmlSchemaValidator.Initialize 매개 변수로 사용하는 XmlSchemaObject 메서드는 부분 유효성 검사를 위해 XmlSchemaValidator 개체를 시작 상태로 초기화합니다.
다음 예제에서는 XmlSchemaObject 메서드를 사용하여 부분 유효성 검사를 위해 XmlSchemaValidator.Initialize 초기화됩니다.
orderNumber
스키마 요소는 XmlQualifiedName 개체의 XmlSchemaObjectTable 속성에서 반환된 GlobalElements 컬렉션에서 XmlSchemaSet 스키마 요소를 선택하여 전달됩니다. 그런 다음 XmlSchemaValidator 개체는 이 특정 요소의 유효성을 검사합니다.
Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
schemaSet.Add(Nothing, "schema.xsd")
schemaSet.Compile()
Dim nameTable As NameTable = New NameTable()
Dim manager As XmlNamespaceManager = New XmlNamespaceManager(nameTable)
Dim validator As XmlSchemaValidator = New XmlSchemaValidator(nameTable, schemaSet, manager, XmlSchemaValidationFlags.None)
validator.Initialize(schemaSet.GlobalElements.Item(New XmlQualifiedName("orderNumber")))
validator.ValidateElement("orderNumber", "", Nothing)
validator.ValidateEndOfAttributes(Nothing)
validator.ValidateText("123")
validator.ValidateEndElement(Nothing)
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "schema.xsd");
schemaSet.Compile();
NameTable nameTable = new NameTable();
XmlNamespaceManager manager = new XmlNamespaceManager(nameTable);
XmlSchemaValidator validator = new XmlSchemaValidator(nameTable, schemaSet, manager, XmlSchemaValidationFlags.None);
validator.Initialize(schemaSet.GlobalElements[new XmlQualifiedName("orderNumber")]);
validator.ValidateElement("orderNumber", "", null);
validator.ValidateEndOfAttributes(null);
validator.ValidateText("123");
validator.ValidateEndElement(null);
이 예제에서는 다음 XML 스키마를 입력으로 사용합니다.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="orderNumber" type="xs:int" />
</xs:schema>
Initialize 메서드에 대한 자세한 내용은 XmlSchemaValidator 클래스 참조 설명서를 참조하세요.
추가 스키마 추가
AddSchema 클래스의 XmlSchemaValidator 메서드는 유효성 검사 중에 사용되는 스키마 집합에 XML 스키마를 추가하는 데 사용됩니다. AddSchema 메서드를 사용하여 유효성을 검사하는 XML 정보 세트에서 인라인 XML 스키마가 발생하는 효과를 시뮬레이션할 수 있습니다.
비고
XmlSchema 매개 변수의 대상 네임스페이스는 XmlSchemaValidator 개체에서 이미 발생한 요소 또는 특성의 네임스페이스와 일치할 수 없습니다.
XmlSchemaValidationFlags.ProcessInlineSchema 값이 XmlSchemaValidator 생성자에 매개 변수로 전달되지 않은 경우 AddSchema 메서드는 아무 작업도 수행하지 않습니다.
AddSchema 메서드의 결과는 유효성을 검사하는 현재 XML 노드 컨텍스트에 따라 달라집니다. 유효성 검사 컨텍스트에 대한 자세한 내용은 이 항목의 "유효성 검사 컨텍스트" 섹션을 참조하세요.
AddSchema 메서드에 대한 자세한 내용은 XmlSchemaValidator 클래스 참조 설명서를 참조하세요.
요소, 특성 및 콘텐츠 유효성 검사
XmlSchemaValidator 클래스는 XML 스키마에 대해 XML 정보 세트의 요소, 특성 및 콘텐츠의 유효성을 검사하는 데 사용되는 몇 가지 메서드를 제공합니다. 다음 표에서는 이러한 각 메서드에 대해 설명합니다.
메서드 | 설명 |
---|---|
ValidateElement | 현재 컨텍스트에서 요소 이름의 유효성을 검사합니다. |
ValidateAttribute | 현재 요소 컨텍스트 또는 XmlSchemaAttribute 메서드에 매개 변수로 전달된 Initialize 개체에 대해 특성의 유효성을 검사합니다. |
ValidateEndOfAttributes | 요소 컨텍스트의 모든 필수 특성이 있는지 확인하고 요소의 자식 콘텐츠의 유효성을 검사하기 위해 XmlSchemaValidator 개체를 준비합니다. |
ValidateText | 현재 요소 컨텍스트에서 텍스트가 허용되는지 여부를 확인하고 현재 요소에 간단한 콘텐츠가 있는 경우 유효성 검사를 위해 텍스트를 누적합니다. |
ValidateWhitespace | 현재 요소 컨텍스트에서 공백이 허용되는지 여부를 확인하고 현재 요소에 간단한 콘텐츠가 있는지 유효성을 검사하기 위해 공백을 누적합니다. |
ValidateEndElement | 단순 콘텐츠가 있는 요소의 데이터 형식에 따라 요소의 텍스트 콘텐츠가 유효한지 확인하고 복잡한 콘텐츠가 있는 요소에 대해 현재 요소의 콘텐츠가 완료되었는지 확인합니다. |
SkipToEndElement | 현재 요소 콘텐츠의 유효성 검사를 건너뛰고 XmlSchemaValidator 개체를 준비하여 부모 요소의 컨텍스트에서 콘텐츠의 유효성을 검사합니다. |
EndValidation | 유효성 검사를 종료하고 ProcessIdentityConstraints 유효성 검사 옵션이 설정된 경우 전체 XML 문서에 대한 ID 제약 조건을 확인합니다. |
비고
XmlSchemaValidator 클래스에는 이전 표에 설명된 각 메서드에 대한 호출 시퀀스 및 발생을 적용하는 정의된 상태 전환이 있습니다. XmlSchemaValidator 클래스의 특정 상태 전환은 이 항목의 "XmlSchemaValidator 상태 전환" 섹션에 설명되어 있습니다.
XML 정보 세트의 요소, 특성 및 콘텐츠의 유효성을 검사하는 데 사용되는 메서드의 예제는 이전 섹션의 예제를 참조하세요. 이러한 메서드에 대한 자세한 내용은 XmlSchemaValidator 클래스 참조 설명서를 참조하세요.
XmlValueGetter를 사용하여 콘텐츠 유효성 검사
이 XmlValueGetterdelegate
특성, 텍스트 또는 공백 노드의 값을 특성, 텍스트 또는 공백 노드의 XSD(XML 스키마 정의 언어) 형식과 호환되는 CLR(공용 언어 런타임) 형식으로 전달하는 데 사용할 수 있습니다. CLR 값이 이미 사용 가능한 경우, 속성, 텍스트 또는 공백 노드에 대해 XmlValueGetterdelegate
을 사용하는 것이 유용하며, 이를 string
로 변환한 후 유효성 검사를 위해 다시 파싱하는 비용을 피할 수 있습니다.
ValidateAttribute, ValidateText및 ValidateWhitespace 메서드가 오버로드되고 특성, 텍스트 또는 공백 노드의 값을 string
또는 XmlValueGetterdelegate
허용합니다.
XmlSchemaValidator 클래스의 다음 메서드는 매개 변수로 XmlValueGetterdelegate
허용합니다.
다음은 소개의 XmlValueGetter 클래스 예제에서 가져온 delegate
XmlSchemaValidator 예제입니다.
XmlValueGetter
delegate
특성 값을 DateTime 개체로 반환합니다.
DateTime반환된 이 XmlValueGetter 개체의 유효성을 검사하기 위해 XmlSchemaValidator 개체는 먼저 특성의 데이터 형식에 대한 ValueType(ValueType은 XSD 형식의 기본 CLR 매핑)으로 변환한 다음 변환된 값에 대한 패싯을 확인합니다.
Shared dateTimeGetterContent As Object
Shared Function DateTimeGetterHandle() As Object
Return dateTimeGetterContent
End Function
Shared Function DateTimeGetter(dateTime As DateTime) As XmlValueGetter
dateTimeGetterContent = dateTime
Return New XmlValueGetter(AddressOf DateTimeGetterHandle)
End Function
static object dateTimeGetterContent;
static object DateTimeGetterHandle()
{
return dateTimeGetterContent;
}
static XmlValueGetter DateTimeGetter(DateTime dateTime)
{
dateTimeGetterContent = dateTime;
return new XmlValueGetter(dateTimeGetterHandle);
}
XmlValueGetter
delegate
대한 전체 예제는 소개의 예제를 참조하세요.
XmlValueGetter
delegate
대한 자세한 내용은 XmlValueGetter및 XmlSchemaValidator 클래스 참조 설명서를 참조하세요.
사후 스키마-Validation-Information
XmlSchemaInfo 클래스는 XmlSchemaValidator 클래스에서 유효성을 검사한 XML 노드의 Post-Schema-Validation-Information 일부를 나타냅니다.
XmlSchemaValidator 클래스의 다양한 메서드는 XmlSchemaInfo 개체를 선택적(null
) out
매개 변수로 허용합니다.
유효성 검사가 성공하면 유효성 검사 결과와 함께 XmlSchemaInfo 개체의 속성이 설정됩니다. 예를 들어 ValidateAttribute 메서드를 사용하여 특성의 유효성을 성공적으로 검사하면 XmlSchemaInfo 개체의(지정된 경우) SchemaAttribute, SchemaType, MemberType및 Validity 속성이 유효성 검사 결과와 함께 설정됩니다.
다음 XmlSchemaValidator 클래스 메서드는 XmlSchemaInfo 개체를 out 매개 변수로 허용합니다.
XmlSchemaInfo 클래스의 전체 예제는 소개의 예제를 참조하세요. XmlSchemaInfo 클래스에 대한 자세한 내용은 XmlSchemaInfo 클래스 참조 설명서를 참조하세요.
예상 파티클, 특성 및 지정되지 않은 기본 특성 검색
XmlSchemaValidator 클래스는 현재 유효성 검사 컨텍스트에서 예상되는 파티클, 특성 및 지정되지 않은 기본 특성을 검색하는 GetExpectedAttributes, GetExpectedParticles및 GetUnspecifiedDefaultAttributes 메서드를 제공합니다.
예상 입자 검색
GetExpectedParticles 메서드는 현재 요소 컨텍스트에서 예상되는 파티클을 포함하는 XmlSchemaParticle 개체의 배열을 반환합니다. GetExpectedParticles 메서드에서 반환할 수 있는 유효한 파티클은 XmlSchemaElement 및 XmlSchemaAny 클래스의 인스턴스입니다.
콘텐츠 모델의 컴포지터가 xs:sequence
일 경우, 시퀀스에서 다음 파티클만 반환됩니다. 콘텐츠 모델의 작성기가 xs:all
또는 xs:choice
경우 현재 요소 컨텍스트에서 따를 수 있는 모든 유효한 파티클이 반환됩니다.
비고
GetExpectedParticles 메서드를 호출한 직후 Initialize 메서드가 호출되면 GetExpectedParticles 메서드는 모든 전역 요소를 반환합니다.
예를 들어 다음 XSD(XML 스키마 정의 언어) 스키마 및 XML 문서에서 book
요소의 유효성을 검사한 후 book
요소는 현재 요소 컨텍스트입니다.
GetExpectedParticles 메서드는 XmlSchemaElement 요소를 나타내는 단일 title
개체를 포함하는 배열을 반환합니다. 유효성 검사 컨텍스트가 title
요소인 경우 GetExpectedParticles 메서드는 빈 배열을 반환합니다.
GetExpectedParticles 요소의 유효성을 검사한 후에 title
메서드가 호출되지만 description
요소의 유효성을 검사하기 전에 XmlSchemaElement 요소를 나타내는 단일 description
개체가 포함된 배열을 반환합니다.
GetExpectedParticles 요소의 유효성을 검사한 후 description
메서드가 호출되면 와일드카드를 나타내는 단일 XmlSchemaAny 개체가 포함된 배열을 반환합니다.
Dim reader As XmlReader = XmlReader.Create("input.xml")
Dim schemaSet As New XmlSchemaSet()
schemaSet.Add(Nothing, "schema.xsd")
Dim manager As New XmlNamespaceManager(reader.NameTable)
Dim validator As New XmlSchemaValidator(reader.NameTable,schemaSet,manager,XmlSchemaValidationFlags.None)
validator.Initialize()
validator.ValidateElement("book", "", Nothing)
validator.ValidateEndOfAttributes(Nothing)
For Each element As XmlSchemaElement In validator.GetExpectedParticles()
Console.WriteLine(element.Name)
Next
validator.ValidateElement("title", "", Nothing)
validator.ValidateEndOfAttributes(Nothing)
For Each element As XmlSchemaElement In validator.GetExpectedParticles()
Console.WriteLine(element.Name)
Next
validator.ValidateEndElement(Nothing)
For Each element As XmlSchemaElement In validator.GetExpectedParticles()
Console.WriteLine(element.Name)
Next
validator.ValidateElement("description", "", Nothing)
validator.ValidateEndOfAttributes(Nothing)
validator.ValidateEndElement(Nothing)
For Each particle As XmlSchemaParticle In validator.GetExpectedParticles()
Console.WriteLine(particle.GetType())
Next
validator.ValidateElement("namespace", "", Nothing)
validator.ValidateEndOfAttributes(Nothing)
validator.ValidateEndElement(Nothing)
validator.ValidateEndElement(Nothing)
XmlReader reader = XmlReader.Create("input.xml");
var schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "schema.xsd");
var manager = new XmlNamespaceManager(reader.NameTable);
var validator = new XmlSchemaValidator(reader.NameTable, schemaSet, manager, XmlSchemaValidationFlags.None);
validator.Initialize();
validator.ValidateElement("book", "", null);
validator.ValidateEndOfAttributes(null);
foreach (XmlSchemaElement element in validator.GetExpectedParticles())
{
Console.WriteLine(element.Name);
}
validator.ValidateElement("title", "", null);
validator.ValidateEndOfAttributes(null);
foreach (XmlSchemaElement element in validator.GetExpectedParticles())
{
Console.WriteLine(element.Name);
}
validator.ValidateEndElement(null);
foreach (XmlSchemaElement element in validator.GetExpectedParticles())
{
Console.WriteLine(element.Name);
}
validator.ValidateElement("description", "", null);
validator.ValidateEndOfAttributes(null);
validator.ValidateEndElement(null);
foreach (XmlSchemaParticle particle in validator.GetExpectedParticles())
{
Console.WriteLine(particle.GetType());
}
validator.ValidateElement("namespace", "", null);
validator.ValidateEndOfAttributes(null);
validator.ValidateEndElement(null);
validator.ValidateEndElement(null);
이 예제에서는 다음 XML을 입력으로 사용합니다.
<xs:schema xmlns:xs="http://www.w3c.org/2001/XMLSchema">
<xs:element name="book">
<xs:sequence>
<xs:element name="title" type="xs:string" />
<xs:element name="description" type="xs:string" />
<xs:any processContent="lax" maxOccurs="unbounded" />
</xs:sequence>
</xs:element>
</xs:schema>
이 예제에서는 다음 XSD 스키마를 입력으로 사용합니다.
<book>
<title>My Book</title>
<description>My Book's Description</description>
<namespace>System.Xml.Schema</namespace>
</book>
비고
GetExpectedParticles 클래스의 GetExpectedAttributes, AddSchema및 XmlSchemaValidator 메서드의 결과는 유효성을 검사하는 현재 컨텍스트에 따라 달라집니다. 자세한 내용은 이 항목의 "유효성 검사 컨텍스트" 섹션을 참조하세요.
GetExpectedParticles 메서드의 예제는 소개의 예제를 참조하세요. GetExpectedParticles 메서드에 대한 자세한 내용은 XmlSchemaValidator 클래스 참조 설명서를 참조하세요.
예상 속성 가져오기
GetExpectedAttributes 메서드는 현재 요소 컨텍스트에서 예상된 특성을 포함하는 XmlSchemaAttribute 개체의 배열을 반환합니다.
예를 들어 소개 예제에서 GetExpectedAttributes 메서드는 book
요소의 모든 특성을 검색하는 데 사용됩니다.
GetExpectedAttributes 메서드 바로 후에 ValidateElement 메서드를 호출하면 XML 문서에 나타날 수 있는 모든 특성이 반환됩니다. 그러나 GetExpectedAttributes 메서드를 하나 이상 호출한 후 ValidateAttribute 메서드를 호출하는 경우 현재 요소에 대해 아직 유효성이 검사되지 않은 특성이 반환됩니다.
비고
GetExpectedParticles 클래스의 GetExpectedAttributes, AddSchema및 XmlSchemaValidator 메서드의 결과는 유효성을 검사하는 현재 컨텍스트에 따라 달라집니다. 자세한 내용은 이 항목의 "유효성 검사 컨텍스트" 섹션을 참조하세요.
GetExpectedAttributes 메서드의 예제는 소개의 예제를 참조하세요. GetExpectedAttributes 메서드에 대한 자세한 내용은 XmlSchemaValidator 클래스 참조 설명서를 참조하세요.
지정되지 않은 기본 특성 검색
GetUnspecifiedDefaultAttributes 메서드는 기본값이지만 요소 컨텍스트에서 ArrayList 메서드를 사용하여 이전에 유효성이 검사되지 않은 어떤 특성이라도 XmlSchemaAttribute 객체가 포함된 ValidateAttribute을 채운다. 요소 컨텍스트의 각 특성에서 GetUnspecifiedDefaultAttributes 메서드를 호출한 후 ValidateAttribute 메서드를 호출해야 합니다. 유효성을 검사할 XML 문서에 삽입할 기본 특성을 결정하는 데 GetUnspecifiedDefaultAttributes 메서드를 사용해야 합니다.
GetUnspecifiedDefaultAttributes 메서드에 대한 자세한 내용은 XmlSchemaValidator 클래스 참조 설명서를 참조하세요.
스키마 유효성 검사 이벤트 처리
유효성 검사 중에 발생하는 스키마 유효성 검사 경고 및 오류는 ValidationEventHandler 클래스의 XmlSchemaValidator 이벤트에서 처리됩니다.
스키마 유효성 검사 경고는 XmlSeverityType 값이 Warning이며, 스키마 유효성 검사 오류는 XmlSeverityType 값이 Error입니다. 할당되지 않은 경우 ValidationEventHandler이면, 모든 스키마 유효성 검사 오류에 대해 XmlSchemaValidationException 값이 XmlSeverityType인 Error이 throw됩니다. 그러나 XmlSchemaValidationException 값이 XmlSeverityType인 경우 스키마 유효성 검사 경고에 대해 Warning이(가) 발생하지 않습니다.
다음은 소개 예제에서 가져온 스키마 유효성 검사 중에 발생하는 스키마 유효성 검사 경고 및 오류를 수신하는 ValidationEventHandler 예입니다.
Shared Sub SchemaValidationEventHandler(sender As Object, e As ValidationEventArgs)
Select Case e.Severity
Case XmlSeverityType.Error
Console.WriteLine(vbCrLf & "Error: {0}", e.Message)
Exit Sub
Case XmlSeverityType.Warning
Console.WriteLine(vbCrLf & "Warning: {0}", e.Message)
Exit Sub
End Select
End Sub
static void SchemaValidationEventHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
Console.WriteLine("\nError: {0}", e.Message);
break;
case XmlSeverityType.Warning:
Console.WriteLine("\nWarning: {0}", e.Message);
break;
}
}
ValidationEventHandler대한 전체 예제는 소개의 예제를 참조하세요. 자세한 내용은 XmlSchemaInfo 클래스 참조 설명서를 참조하세요.
XmlSchemaValidator 상태 전환
XmlSchemaValidator 클래스에는 XML 정보 세트의 요소, 특성 및 콘텐츠의 유효성을 검사하는 데 사용되는 각 메서드에 대한 호출 시퀀스 및 발생을 적용하는 정의된 상태 전환이 있습니다.
다음 표에서는 XmlSchemaValidator 클래스의 상태 전환과 각 상태에서 수행할 수 있는 메서드 호출의 시퀀스 및 발생에 대해 설명합니다.
주 | 전환 |
---|---|
확인 | Initialize(ValidateAttribute | TopLevel*) EndValidation |
최상위 | ValidateWhitespace | ValidateText | 요소 |
요소 |
ValidateElement
ValidateAttribute* (ValidateEndOfAttributes 콘텐츠*)? ValidateEndElement | ValidateElement ValidateAttribute * SkipToEndElement | ValidateElement ValidateAttribute * ValidateEndOfAttributes 콘텐츠* SkipToEndElement | |
콘텐츠 | ValidateWhitespace | ValidateText | 요소 |
비고
InvalidOperationException 객체의 현재 상태에 맞지 않게 메서드 호출이 잘못된 순서로 이루어질 경우, 위의 표에 나와 있는 각 메서드에 의해 XmlSchemaValidator이(가) 던져집니다.
위의 상태 전환 테이블은 문장 부호 기호를 사용하여 XmlSchemaValidator 클래스의 상태 전환의 각 상태에 대해 호출할 수 있는 메서드 및 기타 상태를 설명합니다. 사용되는 기호는 DTD(문서 형식 정의)에 대한 XML 표준 참조에 있는 것과 동일한 기호입니다.
다음 표에서는 위의 상태 전환 테이블에 있는 문장 부호 기호가 XmlSchemaValidator 클래스의 상태 전환에서 각 상태에 대해 호출할 수 있는 메서드 및 기타 상태에 미치는 영향을 설명합니다.
기호 | 설명 |
---|---|
| | 메서드 또는 상태(막대 앞의 메서드 또는 그 뒤의 상태)를 호출할 수 있습니다. |
? | 물음표 앞에 오는 메서드 또는 상태는 선택 사항이지만 호출되는 경우 한 번만 호출할 수 있습니다. |
* | * 기호 앞에 오는 메서드 또는 상태는 선택 사항이며 두 번 이상 호출할 수 있습니다. |
유효성 검사 컨텍스트
XML 정보 세트의 요소, 특성 및 콘텐츠의 유효성을 검사하고 XmlSchemaValidator 개체의 유효성 검사 컨텍스트를 변경하는 데 사용되는 XmlSchemaValidator 클래스의 메서드입니다. 예를 들어 SkipToEndElement 메서드는 현재 요소 콘텐츠의 유효성 검사를 건너뛰고 부모 요소의 컨텍스트에서 콘텐츠의 유효성을 검사하도록 XmlSchemaValidator 개체를 준비합니다. 현재 요소의 모든 자식에 대한 유효성 검사를 건너뛰고 ValidateEndElement 메서드를 호출하는 것과 같습니다.
GetExpectedParticles 클래스의 GetExpectedAttributes, AddSchema및 XmlSchemaValidator 메서드의 결과는 유효성을 검사하는 현재 컨텍스트에 따라 달라집니다.
다음 표에서는 XML 정보 세트의 요소, 특성 및 콘텐츠의 유효성을 검사하는 데 사용되는 XmlSchemaValidator 클래스의 메서드 중 하나를 호출한 후 이러한 메서드를 호출한 결과를 설명합니다.
메서드 | 예상 입자 가져오기 | 예상 속성 가져오기 | 스키마 추가 |
---|---|---|---|
Initialize | 기본 Initialize 메서드가 호출되면 GetExpectedParticles 모든 전역 요소가 포함된 배열을 반환합니다. Initialize 매개 변수로 사용하는 오버로드된 XmlSchemaObject 메서드를 호출하여 요소의 부분 유효성 검사를 초기화하는 경우 GetExpectedParticlesXmlSchemaValidator 개체가 초기화된 요소만 반환합니다. |
기본 Initialize 메서드가 호출되면 GetExpectedAttributes 빈 배열을 반환합니다. Initialize 매개 변수로 사용하는 XmlSchemaObject 메서드의 오버로드가 호출되어 특성의 부분 유효성 검사를 초기화하는 경우 GetExpectedAttributesXmlSchemaValidator 개체가 초기화된 특성만 반환합니다. |
전처리 오류가 없는 경우 XmlSchemaSet 개체의 XmlSchemaValidator 스키마를 추가합니다. |
ValidateElement | 컨텍스트 요소가 유효한 경우 GetExpectedParticles 컨텍스트 요소의 자식으로 예상되는 요소의 시퀀스를 반환합니다. 컨텍스트 요소가 잘못된 경우 GetExpectedParticles 빈 배열을 반환합니다. |
컨텍스트 요소가 유효하고 이전에 ValidateAttribute 호출하지 않은 경우 GetExpectedAttributes 컨텍스트 요소에 정의된 모든 특성 목록을 반환합니다. 일부 특성의 유효성이 이미 검사된 경우 GetExpectedAttributes 유효성을 검사할 나머지 특성 목록을 반환합니다. 컨텍스트 요소가 잘못된 경우 GetExpectedAttributes 빈 배열을 반환합니다. |
위와 동일합니다. |
ValidateAttribute | 컨텍스트 특성이 최상위 특성인 경우 GetExpectedParticles 빈 배열을 반환합니다. 그렇지 않으면 GetExpectedParticles 컨텍스트 요소의 첫 번째 자식으로 예상되는 요소의 시퀀스를 반환합니다. |
컨텍스트 특성이 최상위 특성인 경우 GetExpectedAttributes 빈 배열을 반환합니다. 그렇지 않으면 GetExpectedAttributes 유효성을 검사할 나머지 특성 목록을 반환합니다. |
위와 동일합니다. |
GetUnspecifiedDefaultAttributes | GetExpectedParticles 컨텍스트 요소의 첫 번째 자식으로 예상되는 요소의 시퀀스를 반환합니다. | GetExpectedAttributes 컨텍스트 요소에 대해 아직 유효성을 검사하지 않은 필수 및 선택적 특성 목록을 반환합니다. | 위와 동일합니다. |
ValidateEndOfAttributes | GetExpectedParticles 컨텍스트 요소의 첫 번째 자식으로 예상되는 요소의 시퀀스를 반환합니다. | GetExpectedAttributes 빈 배열을 반환합니다. | 위와 동일합니다. |
ValidateText | 컨텍스트 요소의 contentType이 Mixed이면 GetExpectedParticles 다음 위치에 필요한 요소의 시퀀스를 반환합니다. 컨텍스트 요소의 contentType이 TextOnly 또는 Empty이면 GetExpectedParticles 빈 배열을 반환합니다. 컨텍스트 요소의 contentType이 ElementOnly이면 GetExpectedParticles 다음 위치에 필요한 요소의 시퀀스를 반환하지만 유효성 검사 오류가 이미 발생했습니다. |
GetExpectedAttributes 유효성이 검사되지 않은 컨텍스트 요소의 특성 목록을 반환합니다. | 위와 동일합니다. |
ValidateWhitespace | 컨텍스트 공백이 최상위 공백인 경우 GetExpectedParticles 빈 배열을 반환합니다. 그렇지 않으면 GetExpectedParticles 메서드의 동작은 ValidateText과 동일합니다. |
컨텍스트 공백이 최상위 공백인 경우 GetExpectedAttributes 빈 배열을 반환합니다. 그렇지 않으면 GetExpectedAttributes 메서드의 동작은 ValidateText과 동일합니다. |
위와 동일합니다. |
ValidateEndElement | GetExpectedParticles는 컨텍스트 요소(가능한 형제 요소)의 뒤에 나올 것으로 예상되는 요소들의 순서를 반환합니다. |
GetExpectedAttributes 유효성이 검사되지 않은 컨텍스트 요소의 특성 목록을 반환합니다. 컨텍스트 요소에 부모가 없으면 GetExpectedAttributes 빈 목록을 반환합니다(컨텍스트 요소는 ValidateEndElement 호출된 현재 요소의 부모임). |
위와 동일합니다. |
SkipToEndElement | ValidateEndElement와 동일합니다. | ValidateEndElement와 동일합니다. | 위와 동일합니다. |
EndValidation | 빈 배열을 반환합니다. | 빈 배열을 반환합니다. | 위와 동일합니다. |
비고
XmlSchemaValidator 클래스의 다양한 속성에서 반환되는 값은 위의 표에 있는 메서드를 호출하여 변경되지 않습니다.
참고하십시오
.NET