DOM における XML ドキュメントの検証Validating an XML Document in the DOM

既定では、XmlDocument クラスは、ドキュメント オブジェクト モデル (DOM) 内の XML ドキュメントを XML スキーマ定義言語 (XSD) スキーマまたはドキュメント型定義 (DTD) に対して検証しません。XML が整形式であることだけが検証されます。The XmlDocument class does not validate the XML in the Document Object Model (DOM) against an XML Schema definition language (XSD) schema or document type definition (DTD) by default; the XML is only verified to be well-formed.

DOM 内の XML を検証するには、スキーマ検証型 XmlReaderLoad クラスの XmlDocument メソッドに渡して、DOM への読み込み時に XML を検証するか、Validate クラスの XmlDocument メソッドを使用して、まだ未検証の DOM 内の XML ドキュメントを検証することができます。To validate the XML in the DOM, you can validate the XML as it is loaded into the DOM by passing a schema-validating XmlReader to the Load method of the XmlDocument class, or validate a previously unvalidated XML document in the DOM using the Validate method of the XmlDocument class.

DOM への読み込み時の XML ドキュメントの検証Validating an XML Document As It Is Loaded into the DOM

検証型 XmlDocumentXmlReader クラスの Load メソッドに渡されると、XmlDocument クラスは DOM への読み込み時に XML データを検証します。The XmlDocument class validates the XML data as it is loaded into the DOM when a validating XmlReader is passed to the Load method of the XmlDocument class.

検証が正常に終了すると、スキーマの既定値が適用され、必要に応じてテキスト値がアトミック値に変換され、型情報が検証済みの情報項目に関連付けられます。After successful validation, schema defaults are applied, text values are converted to atomic values as necessary, and type information is associated with validated information items. その結果、以前の型指定されていない XML データは、型指定された XML データに置き換わります。As a result, typed XML data replaces previously untyped XML data.

XML スキーマ検証型 XmlReader の作成Creating an XML Schema-Validating XmlReader

XML スキーマ検証型 XmlReader を作成するには、次の手順を実行します。To create an XML schema-validating XmlReader, follow these steps.

  1. 新しい XmlReaderSettings インスタンスを作成します。Construct a new XmlReaderSettings instance.

  2. XML スキーマを Schemas インスタンスの XmlReaderSettings プロパティに追加します。Add an XML schema to the Schemas property of the XmlReaderSettings instance.

  3. SchemaValidationType として指定します。Specify Schema as the ValidationType.

  4. オプションとして、検証中に検出したスキーマ検証エラーおよび警告を処理する ValidationFlagsValidationEventHandler を指定します。Optionally specify ValidationFlags and a ValidationEventHandler to handle schema validation errors and warnings encountered during validation.

  5. 最後に、XmlReaderSettings オブジェクトを、スキーマ検証型 Create を作成する XmlReader クラスの XmlReader メソッドに、XML ドキュメントと共に渡します。Finally, pass the XmlReaderSettings object to the Create method of the XmlReader class along with the XML document, creating a schema-validating XmlReader.

Example

次のコード サンプルでは、スキーマ検証型 XmlReader が DOM に読み込まれた XML データを検証します。In the code example that follows, a schema-validating XmlReader validates the XML data loaded into the DOM. 無効な変更を加えられた後、XML ドキュメントが再検証され、スキーマ検証エラーが発生します。Invalid modifications are made to the XML document and the document is then revalidated, causing schema validation errors. 最後に、エラーの 1 つが修正された後、XML ドキュメントの一部が部分的に検証されます。Finally, one of the errors is corrected, and then part of the XML document is partially validated.

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Schema;

ref class XmlDocumentValidationExample
{
public:

    static void Main()
    {
        try
        {
            // Create a schema validating XmlReader.
            XmlReaderSettings^ settings = gcnew XmlReaderSettings();
            settings->Schemas->Add("http://www.contoso.com/books", "contosoBooks.xsd");
			ValidationEventHandler^ eventHandler = gcnew ValidationEventHandler(ValidationEventHandlerOne);
            settings->ValidationEventHandler += eventHandler;
			settings->ValidationFlags = settings->ValidationFlags | XmlSchemaValidationFlags::ReportValidationWarnings;
			settings->ValidationType = ValidationType::Schema;

			XmlReader^ reader = XmlReader::Create("contosoBooks.xml", settings);

            // The XmlDocument validates the XML document contained
            // in the XmlReader as it is loaded into the DOM.
            XmlDocument^ document = gcnew XmlDocument();
            document->Load(reader);

            // Make an invalid change to the first and last 
            // price elements in the XML document, and write
            // the XmlSchemaInfo values assigned to the price
            // element during load validation to the console.
            XmlNamespaceManager^ manager = gcnew XmlNamespaceManager(document->NameTable);
            manager->AddNamespace("bk", "http://www.contoso.com/books");

            XmlNode^ priceNode = document->SelectSingleNode("/bk:bookstore/bk:book/bk:price", manager);

            Console::WriteLine("SchemaInfo.IsDefault: {0}", priceNode->SchemaInfo->IsDefault);
            Console::WriteLine("SchemaInfo.IsNil: {0}", priceNode->SchemaInfo->IsNil);
            Console::WriteLine("SchemaInfo.SchemaElement: {0}", priceNode->SchemaInfo->SchemaElement);
            Console::WriteLine("SchemaInfo.SchemaType: {0}", priceNode->SchemaInfo->SchemaType);
            Console::WriteLine("SchemaInfo.Validity: {0}", priceNode->SchemaInfo->Validity);

            priceNode->InnerXml = "A";

            XmlNodeList^ priceNodes = document->SelectNodes("/bk:bookstore/bk:book/bk:price", manager);
            XmlNode^ lastprice = priceNodes[priceNodes->Count - 1];
            
            lastprice->InnerXml = "B";

            // Validate the XML document with the invalid changes.
            // The invalid changes cause schema validation errors.
            document->Validate(eventHandler);

            // Correct the invalid change to the first price element.
            priceNode->InnerXml = "8.99";

            // Validate only the first book element. The last book
            // element is invalid, but not included in validation.
            XmlNode^ bookNode = document->SelectSingleNode("/bk:bookstore/bk:book", manager);
            document->Validate(eventHandler, bookNode);
        }
        catch (XmlException^ ex)
        {
            Console::WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex->Message);
        }
        catch(XmlSchemaValidationException^ ex)
        {
            Console::WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex->Message);
        }
        catch (Exception^ ex)
        {
            Console::WriteLine("XmlDocumentValidationExample.Exception: {0}", ex->Message);
        }
    }

    static void ValidationEventHandlerOne(Object^ sender, ValidationEventArgs^ args)
    {
		if (args->Severity == XmlSeverityType::Warning)
            Console::Write("\nWARNING: ");
		else if (args->Severity == XmlSeverityType::Error)
            Console::Write("\nERROR: ");

        Console::WriteLine(args->Message);
    }
};

int main()
{
	XmlDocumentValidationExample::Main();
    return 0;
}
using System;
using System.Xml;
using System.Xml.Schema;

class XmlDocumentValidationExample
{
    static void Main(string[] args)
    {
        try
        {
            // Create a schema validating XmlReader.
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
            settings.ValidationFlags = settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationType = ValidationType.Schema;

            XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);

            // The XmlDocument validates the XML document contained
            // in the XmlReader as it is loaded into the DOM.
            XmlDocument document = new XmlDocument();
            document.Load(reader);

            // Make an invalid change to the first and last 
            // price elements in the XML document, and write
            // the XmlSchemaInfo values assigned to the price
            // element during load validation to the console.
            XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
            manager.AddNamespace("bk", "http://www.contoso.com/books");

            XmlNode priceNode = document.SelectSingleNode(@"/bk:bookstore/bk:book/bk:price", manager);

            Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault);
            Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil);
            Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement);
            Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType);
            Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity);

            priceNode.InnerXml = "A";

            XmlNodeList priceNodes = document.SelectNodes(@"/bk:bookstore/bk:book/bk:price", manager);
            XmlNode lastprice = priceNodes[priceNodes.Count - 1];
            
            lastprice.InnerXml = "B";

            // Validate the XML document with the invalid changes.
            // The invalid changes cause schema validation errors.
            document.Validate(ValidationEventHandler);

            // Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99";

            // Validate only the first book element. The last book
            // element is invalid, but not included in validation.
            XmlNode bookNode = document.SelectSingleNode(@"/bk:bookstore/bk:book", manager);
            document.Validate(ValidationEventHandler, bookNode);
        }
        catch (XmlException ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message);
        }
        catch(XmlSchemaValidationException ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message);
        }
    }

    static void ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("\nWARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("\nERROR: ");

        Console.WriteLine(args.Message);
    }
}
Imports System
Imports System.Xml
Imports System.Xml.Schema

Class XmlDocumentValidationExample

    Shared Sub Main()

        Try

            ' Create a schema validating XmlReader.
            Dim settings As XmlReaderSettings = New XmlReaderSettings()
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")
            AddHandler settings.ValidationEventHandler, New ValidationEventHandler(AddressOf ValidationEventHandler)
            settings.ValidationFlags = settings.ValidationFlags And XmlSchemaValidationFlags.ReportValidationWarnings
            settings.ValidationType = ValidationType.Schema

            Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings)

            ' The XmlDocument validates the XML document contained
            ' in the XmlReader as it is loaded into the DOM.
            Dim document As XmlDocument = New XmlDocument()
            document.Load(reader)

            ' Make an invalid change to the first and last 
            ' price elements in the XML document, and write
            ' the XmlSchemaInfo values assigned to the price
            ' element during load validation to the console.
            Dim manager As XmlNamespaceManager = New XmlNamespaceManager(document.NameTable)
            manager.AddNamespace("bk", "http://www.contoso.com/books")

            Dim priceNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book/bk:price", manager)

            Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault)
            Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil)
            Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement)
            Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType)
            Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity)

            priceNode.InnerXml = "A"

            Dim priceNodes As XmlNodeList = document.SelectNodes("/bk:bookstore/bk:book/bk:price", manager)
            Dim lastprice As XmlNode = priceNodes(priceNodes.Count - 1)

            lastprice.InnerXml = "B"

            ' Validate the XML document with the invalid changes.
            ' The invalid changes cause schema validation errors.
            document.Validate(AddressOf ValidationEventHandler)

            ' Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99"

            ' Validate only the first book element. The last book
            ' element is invalid, but not included in validation.
            Dim bookNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book", manager)
            document.Validate(AddressOf ValidationEventHandler, bookNode)

        Catch ex As XmlException
            Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message)

        Catch ex As XmlSchemaValidationException
            Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message)

        Catch ex As Exception
            Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message)

        End Try

    End Sub

    Shared Sub ValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)

        If args.Severity = XmlSeverityType.Warning Then
            Console.Write(vbCrLf & "WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write(vbCrLf & "ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)

    End Sub

End Class

この例は、contosoBooks.xml ファイルを入力として使用します。The example takes the contosoBooks.xml file as input.

<?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 ファイルも入力として使用します。The example also takes the contosoBooks.xsd file as input.

<?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>

DOM への読み込み時に XML データを検証する場合は、以下を検討します。Consider the following when validating XML data as it is loaded into the DOM.

  • 上の例では、無効な型が見つかるたびに ValidationEventHandler が呼び出されます。In the above example, the ValidationEventHandler is called whenever an invalid type is encountered. 検証を行う ValidationEventHandlerXmlReader を設定しなかった場合は、XmlSchemaValidationException を呼び出したときに属性や要素の型が検証スキーマで指定されている型と一致しないと、Load がスローされます。If a ValidationEventHandler is not set on the validating XmlReader,an XmlSchemaValidationException is thrown when Load is called if any attribute or element type does not match the corresponding type specified in the validating schema.

  • XML ドキュメントが既定値を定義した関連付けられたスキーマと共に XmlDocument オブジェクトに読み込まれる場合、XmlDocument は、これらの既定値があたかも XML ドキュメント内にあるかのように扱います。When an XML document is loaded into an XmlDocument object with an associated schema that defines default values, the XmlDocument treats these defaults as if they appeared in the XML document. これは、スキーマから既定値を得た要素に対して IsEmptyElement プロパティは常に false を返すことを意味します。This means that the IsEmptyElement property always returns false for an element that was defaulted from the schema. XML ドキュメント内で空要素として書かれている場合も同様です。Even if in the XML document, it was written as an empty element.

DOM における XML ドキュメントの検証Validating an XML Document in the DOM

Validate クラスの XmlDocument メソッドは、DOM に読み込まれた XML データを XmlDocument オブジェクトの Schemas プロパティに対して検証します。The Validate method of the XmlDocument class validates the XML data loaded in the DOM against the schemas in the XmlDocument object's Schemas property. 検証が正常に終了すると、スキーマの既定値が適用され、必要に応じてテキスト値がアトミック値に変換され、型情報が検証済みの情報項目に関連付けられます。After successful validation, schema defaults are applied, text values are converted to atomic values as necessary, and type information is associated with validated information items. その結果、以前の型指定されていない XML データは、型指定された XML データに置き換わります。As a result, typed XML data replaces previously untyped XML data.

以下の例は、上記の「DOM への読み込み時の XML ドキュメントの検証」の例に似ています。The example below is similar to the example in "Validating an XML Document As It Is Loaded into the DOM" above. この例では、XML ドキュメントは DOM への読み込み時には検証されませんが、DOM への読み込み後に、Validate クラスの XmlDocument メソッドを使用して検証されます。In this example, the XML document is not validated as it is loaded into the DOM, but rather is validated after it has been loaded into the DOM using the Validate method of the XmlDocument class. Validate メソッドは XML ドキュメントを SchemasXmlDocument プロパティに含まれている XML スキーマに対して検証します。The Validate method validates the XML document against the XML schemas contained in the Schemas property of the XmlDocument. その後、無効な変更を加えられた後、XML ドキュメントが再検証され、スキーマ検証エラーが発生します。Invalid modifications are then made to the XML document, and the document is then revalidated, causing schema validation errors. 最後に、エラーの 1 つが修正された後、XML ドキュメントの一部が部分的に検証されます。Finally, one of the errors is corrected, and then part of the XML document is partially validated.

using System;
using System.Xml;
using System.Xml.Schema;

class XmlDocumentValidationExample
{
    static void Main(string[] args)
    {
        try
        {
            // Create a new XmlDocument instance and load
            // the XML document into the DOM.
            XmlDocument document = new XmlDocument();
            document.Load("contosoBooks.xml");

            // Add the XML schema for the XML document to the
            // Schemas property of the XmlDocument.
            document.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");

            // Validate the XML document loaded into the DOM.
            document.Validate(ValidationEventHandler);

            // Make an invalid change to the first and last 
            // price elements in the XML document, and write
            // the XmlSchemaInfo values assigned to the price
            // element during validation to the console.
            XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
            manager.AddNamespace("bk", "http://www.contoso.com/books");

            XmlNode priceNode = document.SelectSingleNode(@"/bk:bookstore/bk:book/bk:price", manager);

            Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault);
            Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil);
            Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement);
            Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType);
            Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity);

            priceNode.InnerXml = "A";

            XmlNodeList priceNodes = document.SelectNodes(@"/bk:bookstore/bk:book/bk:price", manager);
            XmlNode lastprice = priceNodes[priceNodes.Count - 1];
            
            lastprice.InnerXml = "B";

            // Validate the XML document with the invalid changes.
            // The invalid changes cause schema validation errors.
            document.Validate(ValidationEventHandler);

            // Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99";

            // Validate only the first book element. The last book
            // element is invalid, but not included in validation.
            XmlNode bookNode = document.SelectSingleNode(@"/bk:bookstore/bk:book", manager);
            document.Validate(ValidationEventHandler, bookNode);
        }
        catch (XmlException ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message);
        }
        catch(XmlSchemaValidationException ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message);
        }
    }

    static void ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("\nWARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("\nERROR: ");

        Console.WriteLine(args.Message);
    }
}
Imports System
Imports System.Xml
Imports System.Xml.Schema

Class XmlDocumentValidationExample

    Shared Sub Main()

        Try

            ' Create a new XmlDocument instance and load
            ' the XML document into the DOM.
            Dim document As XmlDocument = New XmlDocument()
            document.Load("contosoBooks.xml")

            ' Add the XML schema for the XML document to the
            ' Schemas property of the XmlDocument.
            document.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")

            ' Validate the XML document loaded into the DOM.
            document.Validate(AddressOf ValidationEventHandler)

            ' Make an invalid change to the first and last 
            ' price elements in the XML document, and write
            ' the XmlSchemaInfo values assigned to the price
            ' element during validation to the console.
            Dim manager As XmlNamespaceManager = New XmlNamespaceManager(document.NameTable)
            manager.AddNamespace("bk", "http://www.contoso.com/books")

            Dim priceNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book/bk:price", manager)

            Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault)
            Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil)
            Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement)
            Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType)
            Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity)

            priceNode.InnerXml = "A"

            Dim priceNodes As XmlNodeList = document.SelectNodes("/bk:bookstore/bk:book/bk:price", manager)
            Dim lastprice As XmlNode = priceNodes(priceNodes.Count - 1)

            lastprice.InnerXml = "B"

            ' Validate the XML document with the invalid changes.
            ' The invalid changes cause schema validation errors.
            document.Validate(AddressOf ValidationEventHandler)

            ' Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99"

            ' Validate only the first book element. The last book
            ' element is invalid, but not included in validation.
            Dim bookNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book", manager)
            document.Validate(AddressOf ValidationEventHandler, bookNode)

        Catch ex As XmlException
            Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message)

        Catch ex As XmlSchemaValidationException
            Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message)

        Catch ex As Exception
            Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message)

        End Try

    End Sub

    Shared Sub ValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)

        If args.Severity = XmlSeverityType.Warning Then
            Console.Write(vbCrLf & "WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write(vbCrLf & "ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)

    End Sub

End Class

この例は入力として、上記の「DOM への読み込み時の XML ドキュメントの検証」で参照されている contosoBooks.xml ファイルと contosoBooks.xsd ファイルを使用します。The example takes as input the contosoBooks.xml and contosoBooks.xsd files referred to in "Validating an XML Document as it is Loaded into the DOM" above.

検証エラーおよび警告の処理Handling Validation Errors and Warnings

XML スキーマ検証エラーは、DOM に読み込まれる XML データの検証時に報告されます。XML schema validation errors are reported when validating XML data loaded in the DOM. XML データ読み込み時の検証中またはまだ未検証の XML ドキュメントの検証時に検出されたスキーマ検証エラーのすべてについて通知されます。You are notified about all schema validation errors found while validating the XML data as it is being loaded, or when validating a previously unvalidated XML document.

検証エラーは ValidationEventHandler によって処理されます。Validation errors are handled by the ValidationEventHandler. ValidationEventHandlerXmlReaderSettings インスタンスに割り当てられているか、Validate クラスの XmlDocument メソッドに渡されている場合、ValidationEventHandler がスキーマ検証エラーを処理します。それ以外の場合は、スキーマ検証エラーの検出時に XmlSchemaValidationException が発生します。If a ValidationEventHandler was assigned to the XmlReaderSettings instance, or passed to the Validate method of the XmlDocument class, the ValidationEventHandler will handle schema validation errors; otherwise an XmlSchemaValidationException is raised when a schema validation error is encountered.

注意

ValidationEventHandler がプロセスを停止する例外を生成しない限り、スキーマ検証エラーが発生しても XML データは DOM に読み込まれます。The XML data is loaded into the DOM despite schema validation errors unless your ValidationEventHandler raises an exception to stop the process.

ReportValidationWarnings フラグが XmlReaderSettings オブジェクトに指定されていない場合、スキーマ検証警告は報告されません。Schema validation warnings are not reported unless the ReportValidationWarnings flag is specified to the XmlReaderSettings object.

ValidationEventHandler を説明する例については、上記の「DOM への読み込み時の XML ドキュメントの検証」と「DOM における XML ドキュメントの検証」を参照してください。For examples illustrating the ValidationEventHandler, see "Validating an XML Document As It Is Loaded into the DOM" and "Validating an XML Document in the DOM" above.

関連項目See also