次の方法で共有


XPathNavigator を使用したスキーマ検証

XmlDocument クラスを使用すると、XmlDocument オブジェクトに含まれる XML コンテンツを 2 つの方法で検証できます。 1 つ目の方法は、検証XmlReader オブジェクトを使用して XML コンテンツを検証することです。2 つ目の方法は、XmlDocument クラスのValidate メソッドを使用することです。 XPathDocument クラスを使用して、XML コンテンツの読み取り専用検証を実行することもできます。

XML データの検証

XmlDocument クラスは、既定で DTD または XML スキーマ定義言語 (XSD) スキーマ検証を使用して XML ドキュメントを検証しません。 XML ドキュメントが整形式であることを確認するだけです。

XML ドキュメントを検証する最初の方法は、検証XmlReader オブジェクトを使用してXmlDocument オブジェクトに読み込まれるドキュメントを検証することです。 2 つ目の方法は、XmlDocument クラスのValidate メソッドを使用して、以前に型指定されていない XML ドキュメントを検証することです。 どちらの場合も、XmlDocument クラスの Validate メソッドを使用して、検証済みの XML ドキュメントに対する変更を再検証できます。

読み込まれたドキュメントの検証

検証XmlReader オブジェクトは、XmlReaderSettings オブジェクトをパラメーターとして受け取るXmlReader クラスのCreate メソッドにXmlReaderSettings オブジェクトを渡すことによって作成されます。 パラメーターとして渡されるXmlReaderSettings オブジェクトには、Schemaに設定されたValidationType プロパティと、Schemas プロパティに追加されたXmlDocument オブジェクトに含まれる XML ドキュメントの XML スキーマがあります。 検証 XmlReader オブジェクトは、 XmlDocument オブジェクトの作成に使用されます。

次の例では、検証XmlReader オブジェクトを使用してXmlDocument オブジェクトを作成することで、XmlDocument オブジェクトに読み込まれるcontosoBooks.xml ファイルを検証します。 XML ドキュメントはスキーマに従って有効であるため、スキーマ検証エラーや警告は生成されません。

Imports System  
Imports System.Xml  
Imports System.Xml.Schema  
Imports System.Xml.XPath  
  
Class ValidatingReaderExample  
  
    Shared Sub Main(ByVal args() As String)  
  
        Try  
            Dim settings As XmlReaderSettings = New XmlReaderSettings()  
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")  
            settings.ValidationType = ValidationType.Schema  
  
            Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings)  
  
            Dim document As XmlDocument = New XmlDocument()  
            document.Load(reader)  
            Dim navigator As XPathNavigator = document.CreateNavigator()  
  
        Catch e As Exception  
            Console.WriteLine("ValidatingReaderExample.Exception: {0}", e.Message)  
        End Try  
  
    End Sub  
  
    Shared Sub SchemaValidationHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)  
  
        Select Case e.Severity  
            Case XmlSeverityType.Error  
                Console.WriteLine("Schema Validation Error: {0}", e.Message)  
                Exit Sub  
            Case XmlSeverityType.Warning  
                Console.WriteLine("Schema Validation Warning: {0}", e.Message)  
                Exit Sub  
        End Select  
  
    End Sub  
  
End Class  
using System;  
using System.Xml;  
using System.Xml.Schema;  
using System.Xml.XPath;  
  
class ValidatingReaderExample  
{  
    static void Main(string[] args)  
    {  
        try  
        {  
            XmlReaderSettings settings = new XmlReaderSettings();  
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");  
            settings.ValidationType = ValidationType.Schema;  
  
            XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);  
  
            XmlDocument document = new XmlDocument();  
            document.Load(reader);  
            XPathNavigator navigator = document.CreateNavigator();  
        }  
        catch (Exception e)  
        {  
            Console.WriteLine("ValidatingReaderExample.Exception: {0}", e.Message);  
        }  
    }  
  
    static void SchemaValidationHandler(object sender, ValidationEventArgs e)  
    {  
        switch (e.Severity)  
        {  
            case XmlSeverityType.Error:  
                Console.WriteLine("Schema Validation Error: {0}", e.Message);  
                break;  
            case XmlSeverityType.Warning:  
                Console.WriteLine("Schema Validation Warning: {0}", e.Message);  
                break;  
        }  
    }  
}  

この例では、 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>

上記の例では、属性または要素の型が検証スキーマで指定された対応する型と一致しない場合、Loadが呼び出されると、XmlSchemaValidationExceptionがスローされます。 検証XmlReaderValidationEventHandlerが設定されている場合、無効な型が検出されるたびにValidationEventHandlerが呼び出されます。

TypedValueinvalid に設定された属性または要素がXPathNavigatorによってアクセスされると、XmlSchemaExceptionがスローされます。

Validity プロパティを使用すると、XPathNavigatorを使用して属性または要素にアクセスするときに、個々の属性または要素が有効かどうかを判断できます。

既定値を定義するスキーマが関連付けられた XmlDocument オブジェクトに XML ドキュメントが読み込まれると、 XmlDocument オブジェクトはこれらの既定値を XML ドキュメントに表示されるかのように扱います。 つまり、XML ドキュメント内で空の要素として書き込まれた場合でも、 IsEmptyElement プロパティは常にスキーマから既定の要素の false を返します。

Validate メソッドを使用したドキュメントの検証

XmlDocument クラスの Validate メソッドは、XmlDocument オブジェクトに含まれる XML ドキュメントを、XmlDocument オブジェクトの Schemas プロパティで指定されたスキーマと照合して、インフォセット拡張を実行します。 結果は、 XmlDocument オブジェクト内の以前に型指定されていない XML ドキュメントが、型指定されたドキュメントに置き換えられます。

XmlDocument オブジェクトは、Validate メソッドにパラメーターとして渡されたValidationEventHandler デリゲートを使用して、スキーマ検証エラーと警告を報告します。

次の例では、XmlDocument オブジェクトに含まれるcontosoBooks.xml ファイルを、XmlDocument オブジェクトのSchemas プロパティに含まれるcontosoBooks.xsd スキーマと照合します。

Imports System  
Imports System.Xml  
Imports System.Xml.Schema  
Imports System.Xml.XPath  
  
Class ValidateExample  
  
    Shared Sub Main(ByVal args() As String)  
  
        Dim document As XmlDocument = New XmlDocument()  
        document.Load("contosoBooks.xml")  
        Dim navigator As XPathNavigator = document.CreateNavigator()  
  
        document.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")  
        Dim validation As ValidationEventHandler = New ValidationEventHandler(AddressOf SchemaValidationHandler)  
  
        document.Validate(validation)  
  
    End Sub  
  
    Shared Sub SchemaValidationHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)  
  
        Select Case e.Severity  
            Case XmlSeverityType.Error  
                Console.WriteLine("Schema Validation Error: {0}", e.Message)  
                Exit Sub  
            Case XmlSeverityType.Warning  
                Console.WriteLine("Schema Validation Warning: {0}", e.Message)  
                Exit Sub  
        End Select  
  
    End Sub  
  
End Class  
using System;  
using System.Xml;  
using System.Xml.Schema;  
using System.Xml.XPath;  
  
class ValidateExample  
{  
    static void Main(string[] args)  
    {  
        XmlDocument document = new XmlDocument();  
        document.Load("contosoBooks.xml");  
        XPathNavigator navigator = document.CreateNavigator();  
  
        document.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");  
        ValidationEventHandler validation = new ValidationEventHandler(SchemaValidationHandler);  
  
        document.Validate(validation);  
    }  
  
    static void SchemaValidationHandler(object sender, ValidationEventArgs e)  
    {  
        switch (e.Severity)  
        {  
            case XmlSeverityType.Error:  
                Console.WriteLine("Schema Validation Error: {0}", e.Message);  
                break;  
            case XmlSeverityType.Warning:  
                Console.WriteLine("Schema Validation Warning: {0}", e.Message);  
                break;  
        }  
    }  
}  

この例では、 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>

変更の検証

XML ドキュメントに変更を加えた後、XmlDocument クラスの Validate メソッドを使用して、XML ドキュメントのスキーマに対する変更を検証できます。

次の例では、検証XmlReader オブジェクトを使用してXmlDocument オブジェクトを作成することで、XmlDocument オブジェクトに読み込まれるcontosoBooks.xml ファイルを検証します。 XML ドキュメントは、スキーマ検証エラーや警告を生成せずに読み込まれると正常に検証されます。 その後、この例では、 contosoBooks.xsd スキーマに従って無効な XML ドキュメントに 2 つの変更を加えます。 最初の変更では無効な子要素が挿入され、スキーマ検証エラーが発生し、2 つ目の変更では、型指定されたノードの値が、例外の結果として発生するノードの型に応じて無効な値に設定されます。

Imports System  
Imports System.Xml  
Imports System.Xml.Schema  
Imports System.Xml.XPath  
  
Class ValidatingReaderExample  
  
    Shared Sub Main(ByVal args() As String)  
  
        Try  
            Dim settings As XmlReaderSettings = New XmlReaderSettings()  
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")  
            settings.ValidationType = ValidationType.Schema  
  
            Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings)  
  
            Dim document As XmlDocument = New XmlDocument()  
            document.Load(reader)  
            Dim navigator As XPathNavigator = document.CreateNavigator()  
  
            Dim validation As ValidationEventHandler = New ValidationEventHandler(AddressOf SchemaValidationHandler)  
  
            navigator.MoveToChild("bookstore", "http://www.contoso.com/books")  
            navigator.MoveToChild("book", "http://www.contoso.com/books")  
            navigator.MoveToChild("author", "http://www.contoso.com/books")  
  
            navigator.AppendChild("<title>Book Title</title>")  
  
            document.Validate(validation)  
  
            navigator.MoveToParent()  
            navigator.MoveToChild("price", "http://www.contoso.com/books")  
            navigator.SetTypedValue(DateTime.Now)  
        Catch e As Exception  
            Console.WriteLine("ValidatingReaderExample.Exception: {0}", e.Message)  
        End Try  
  
    End Sub  
  
    Shared Sub SchemaValidationHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)  
  
        Select Case e.Severity  
            Case XmlSeverityType.Error  
                Console.WriteLine("Schema Validation Error: {0}", e.Message)  
                Exit Sub  
            Case XmlSeverityType.Warning  
                Console.WriteLine("Schema Validation Warning: {0}", e.Message)  
                Exit Sub  
        End Select  
  
    End Sub  
  
End Class  
using System;  
using System.Xml;  
using System.Xml.Schema;  
using System.Xml.XPath;  
  
class ValidatingReaderExample  
{  
    static void Main(string[] args)  
    {  
        try  
        {  
            XmlReaderSettings settings = new XmlReaderSettings();  
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");  
            settings.ValidationType = ValidationType.Schema;  
  
            XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);  
  
            XmlDocument document = new XmlDocument();  
            document.Load(reader);  
            XPathNavigator navigator = document.CreateNavigator();  
  
            ValidationEventHandler validation = new ValidationEventHandler(SchemaValidationHandler);  
  
            navigator.MoveToChild("bookstore", "http://www.contoso.com/books");  
            navigator.MoveToChild("book", "http://www.contoso.com/books");  
            navigator.MoveToChild("author", "http://www.contoso.com/books");  
  
            navigator.AppendChild("<title>Book Title</title>");  
  
            document.Validate(validation);  
  
            navigator.MoveToParent();  
            navigator.MoveToChild("price", "http://www.contoso.com/books");  
            navigator.SetTypedValue(DateTime.Now);  
        }  
        catch (Exception e)  
        {  
            Console.WriteLine("ValidatingReaderExample.Exception: {0}", e.Message);  
        }  
    }  
  
    static void SchemaValidationHandler(object sender, ValidationEventArgs e)  
    {  
        switch (e.Severity)  
        {  
            case XmlSeverityType.Error:  
                Console.WriteLine("Schema Validation Error: {0}", e.Message);  
                break;  
            case XmlSeverityType.Warning:  
                Console.WriteLine("Schema Validation Warning: {0}", e.Message);  
                break;  
        }  
    }  
}  

この例では、 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>

上記の例では、 XmlDocument オブジェクトに含まれる XML ドキュメントに 2 つの変更が加えられます。 XML ドキュメントが読み込まれると、発生したスキーマ検証エラーは検証イベント ハンドラー メソッドによって処理され、コンソールに書き込まれます。

この例では、XML ドキュメントが読み込まれた後に検証エラーが発生し、XmlDocument クラスの Validate メソッドを使用して検出されました。

XPathNavigator クラスのSetTypedValue メソッドを使用して行われた変更は、ノードのスキーマの種類に応じて新しい値が無効であったため、InvalidCastExceptionが発生しました。

SetTypedValue メソッドを使用した値の変更の詳細については、「XPathNavigator を使用した XML データの変更」トピックを参照してください。

Read-Only 検証

XPathDocument クラスは、XML ドキュメントの読み取り専用のメモリ内表現です。 XPathDocument クラスと XmlDocument クラスの両方で、XML ドキュメント内を移動および編集するためのXPathNavigator オブジェクトが作成されます。 XPathDocument クラスは読み取り専用クラスであるため、XPathDocument オブジェクトから返XPathNavigatorオブジェクトは、XPathDocument オブジェクトに含まれる XML ドキュメントを編集できません。

検証の場合は、このトピックで前述したように、検証XmlReader オブジェクトを使用してXmlDocument オブジェクトを作成するのと同じように、XPathDocument オブジェクトを作成できます。 XPathDocument オブジェクトは読み込み時に XML ドキュメントを検証しますが、XPathDocument オブジェクト内の XML データを編集できないため、XML ドキュメントを再検証することはできません。

読み取り専用および編集可能な XPathNavigator オブジェクトの詳細については、「 XPathDocument と XmlDocument を使用した XML データの読み取 り」トピックを参照してください。

こちらも参照ください