Share via


使用 XmlSchemaSet 進行 XML 結構描述 (XSD) 驗證

更新: November 2007

可以根據 XmlSchemaSet 中的 XML 結構描述定義語言 (XSD) 結構描述來驗證 XML 文件。

驗證 XML 文件

XML 文件是透過 XmlReader 類別的 Create 方法來驗證的。若要驗證 XML 文件,請建構 XmlReaderSettings 物件,該物件包含可用於驗證 XML 文件的 XML 結構描述定義語言 (XSD) 結構描述。

注意事項:

System.Xml.Schema 命名空間包含的擴充方法可在使用 LINQ to XML 時,輕鬆地針對 XML 檔案驗證 XML 樹狀結構。如需使用 LINQ to XML 驗證 XML 文件的詳細資訊,請參閱HOW TO:使用 XSD 進行驗證 (LINQ to XML)

可以將個別結構描述或一組結構描述 (當做 XmlSchemaSet) 加入至 XmlSchemaSet,其方式是將其中一個當做參數傳遞給 XmlSchemaSetAdd 方法。請注意在驗證文件時,此文件的目標命名空間必須符合結構描述集內結構描述的目標命名空間。

下列是範例 XML 文件。

<bookstore xmlns="https://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>

下列是驗證範例 XML 文件的結構描述。

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="https://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>

在下面的程式碼範例中,會將以上結構描述加入至 XmlReaderSettings 物件的 XmlSchemaSetSchemas 屬性。將 XmlReaderSettings 物件當做參數,傳遞至驗證以上 XML 文件之 XmlReader 物件的 Create 方法。

XmlReaderSettings 物件的 ValidationType 屬性會設為 Schema,以透過 XmlReader 物件的 Create 方法,來強制驗證 XML 文件。將 ValidationEventHandler 加入至 XmlReaderSettings 物件,以處理在驗證 XML 文件及結構描述期間找到的錯誤所引發的任意 WarningError 事件。

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

Class XmlSchemaSetExample

    Shared Sub Main()

        Dim booksSettings As XmlReaderSettings = New XmlReaderSettings()
        booksSettings.Schemas.Add("https://www.contoso.com/books", "contosoBooks.xsd")
        booksSettings.ValidationType = ValidationType.Schema
        AddHandler booksSettings.ValidationEventHandler, New ValidationEventHandler(AddressOf booksSettingsValidationEventHandler)

        Dim books As XmlReader = XmlReader.Create("contosoBooks.xml", booksSettings)

        While books.Read()

        End While

    End Sub

    Shared Sub booksSettingsValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)

        If e.Severity = XmlSeverityType.Warning Then
            Console.Write("WARNING: ")
            Console.WriteLine(e.Message)

        ElseIf e.Severity = XmlSeverityType.Error Then
            Console.Write("ERROR: ")
            Console.WriteLine(e.Message)
        End If

    End Sub

End Class
using System;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaSetExample
{
    static void Main()
    {
        XmlReaderSettings booksSettings = new XmlReaderSettings();
        booksSettings.Schemas.Add("https://www.contoso.com/books", "contosoBooks.xsd");
        booksSettings.ValidationType = ValidationType.Schema;
        booksSettings.ValidationEventHandler += new ValidationEventHandler(booksSettingsValidationEventHandler);

        XmlReader books = XmlReader.Create("contosoBooks.xml", booksSettings);

        while (books.Read()) { }
    }

    static void booksSettingsValidationEventHandler(object sender, ValidationEventArgs e)
    {
        if (e.Severity == XmlSeverityType.Warning)
        {
            Console.Write("WARNING: ");
            Console.WriteLine(e.Message);
        }
        else if (e.Severity == XmlSeverityType.Error)
        {
            Console.Write("ERROR: ");
            Console.WriteLine(e.Message);
        }
    }
}
#using <System.Xml.dll>

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

static void booksSettingsValidationEventHandler( Object^ /*sender*/, ValidationEventArgs^ e )
{
   if ( e->Severity == XmlSeverityType::Warning )
   {
      Console::Write( L"WARNING: " );
      Console::WriteLine( e->Message );
   }
   else
   if ( e->Severity == XmlSeverityType::Error )
   {
      Console::Write( L"ERROR: " );
      Console::WriteLine( e->Message );
   }
}

int main()
{
   XmlReaderSettings^ booksSettings = gcnew XmlReaderSettings;
   booksSettings->Schemas->Add( L"https://www.contoso.com/books", L"books.xsd" );
   booksSettings->ValidationType = ValidationType::Schema;
   booksSettings->ValidationEventHandler += gcnew ValidationEventHandler( booksSettingsValidationEventHandler );
   XmlReader^ books = XmlReader::Create( L"books.xml", booksSettings );
   while ( books->Read() )
   {}

   return 0;
}

請參閱

概念

用於結構描述編譯的 XmlSchemaSet

其他資源

使用 XML 結構描述