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 オブジェクトの状態を初期化するために使用される 2 つのオーバーロードされた XmlSchemaValidator メソッドがあります。 2 つの 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 State Transition」セクションで説明します。
XML インフォセット内の要素、属性、およびコンテンツを検証するために使用されるメソッドの例については、前のセクションの例を参照してください。 これらのメソッドの詳細については、XmlSchemaValidator クラスのリファレンス ドキュメントを参照してください。
XmlValueGetter を使用したコンテンツの検証
XmlValueGetter
delegate
を使用すると、属性、テキスト、または空白ノードの値を、属性、テキスト、または空白ノードの XML スキーマ定義言語 (XSD) 型と互換性のある共通言語ランタイム (CLR) 型として渡すことができます。
XmlValueGetter
delegate
は、属性、テキスト、または空白ノードの CLR 値が既に使用可能であり、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 参照してください。
スキーマの検証後の情報
XmlSchemaInfo クラスは、XmlSchemaValidator クラスによって検証された XML ノードのスキーマ後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 メソッドはすべてのグローバル要素を返します。
たとえば、後に続く XML スキーマ定義言語 (XSD) スキーマおよび XML ドキュメントでは、book
要素を検証した後、book
要素が現在の要素コンテキストになります。
GetExpectedParticles メソッドは、XmlSchemaElement 要素を表す 1 つの 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 メソッドの 1 つ以上の呼び出しの後に 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 でスローされます。 ただし、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 |
TopLevel | ValidateWhitespace | ValidateText |要素 |
要素 |
ValidateElement
ValidateAttribute* (ValidateEndOfAttributes コンテンツ*)? ValidateEndElement | ValidateElement ValidateAttribute * SkipToEndElement | ValidateElement ValidateAttribute * ValidateEndOfAttributes コンテンツ* SkipToEndElement | |
コンテンツ | ValidateWhitespace | ValidateText |要素 |
注
InvalidOperationException は、XmlSchemaValidator オブジェクトの現在の状態に従ってメソッドの呼び出しが正しくないシーケンスで行われた場合に、上記の表の各メソッドによってスローされます。
上記の状態遷移テーブルでは、句読点記号を使用して、XmlSchemaValidator クラスの状態遷移の各状態に対して呼び出すことができるメソッドとその他の状態について説明します。 使用されるシンボルは、ドキュメント型定義 (DTD) の XML 標準リファレンスに記載されているのと同じシンボルです。
次の表では、上記の状態遷移テーブルにある句読点記号が、XmlSchemaValidator クラスの状態遷移の各状態に対して呼び出すことができるメソッドおよびその他の状態に与える影響について説明します。
記号 | 説明 |
---|---|
| | メソッドまたは状態 (バーの前のメソッドまたはバーの後のメソッド) を呼び出すことができます。 |
? | 疑問符の前にあるメソッドまたは状態は省略可能ですが、呼び出された場合は 1 回だけ呼び出すことができます。 |
* | * 記号の前にあるメソッドまたは状態は省略可能であり、複数回呼び出すことができます。 |
検証コンテキスト
XML 情報セット内の要素、属性、およびコンテンツを検証するために使用される XmlSchemaValidator クラスのメソッドは、XmlSchemaValidator オブジェクトの検証コンテキストを変更します。 たとえば、SkipToEndElement メソッドは、現在の要素のコンテンツの検証をスキップし、親要素のコンテキストでコンテンツを検証するために XmlSchemaValidator オブジェクトを準備します。これは、現在の要素のすべての子の検証をスキップしてから、ValidateEndElement メソッドを呼び出すことと同じです。
GetExpectedParticles クラスの GetExpectedAttributes、AddSchema、および XmlSchemaValidator メソッドの結果は、検証中の現在のコンテキストに依存します。
次の表は、XML 情報セット内の要素、属性、およびコンテンツを検証するために使用される XmlSchemaValidator クラスのいずれかのメソッドを呼び出した後にこれらのメソッドを呼び出した結果を示しています。
メソッド | GetExpectedParticles | GetExpectedAttributes(予想される属性を取得) | スキーマを追加 |
---|---|---|---|
Initialize | 既定の Initialize メソッドが呼び出された場合、GetExpectedParticles はすべてのグローバル要素を含む配列を返します。 Initialize をパラメーターとして受け取るオーバーロードされた XmlSchemaObject メソッドを呼び出して要素の部分的な検証を初期化する場合、GetExpectedParticles は、XmlSchemaValidator オブジェクトが初期化された要素のみを返します。 |
既定の Initialize メソッドが呼び出された場合、GetExpectedAttributes は空の配列を返します。 Initialize をパラメーターとして受け取る XmlSchemaObject メソッドのオーバーロードを呼び出して属性の部分的な検証を初期化する場合、GetExpectedAttributes は、XmlSchemaValidator オブジェクトが初期化された属性のみを返します。 |
前処理エラーがない場合は、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