共用方式為


XmlSchemaValidator 推入型驗證

此類別 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 類別的新實例。

建構函式會採用 XmlSchemaValidatorXmlNameTableXmlSchemaSetXmlNamespaceManager 物件做為參數,以及 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 物件初始化為其部分驗證的起始狀態。

在下列範例中, XmlSchemaObject 會使用 XmlSchemaValidator.Initialize 方法初始化 以進行部分驗證。 架構orderNumber元素會藉由選取 物件 屬性XmlQualifiedNameXmlSchemaObjectTable傳回的集合中的 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 類別參考文件。

新增其他架構

類別 AddSchemaXmlSchemaValidator 方法可用來將 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 檔的身分識別條件約束。

備註

類別 XmlSchemaValidator 具有已定義的狀態轉換,可強制執行對上表所述每個方法的呼叫順序和發生次數。 XmlSchemaValidator類別的特定狀態轉換會在本主題的「XmlSchemaValidator 狀態轉換」一節中描述。

如需用來驗證 XML 資訊集中元素、屬性和內容的方法範例,請參閱上一節中的範例。 如需這些方法的詳細資訊,請參閱 XmlSchemaValidator 類別參考檔。

使用 XmlValueGetter 驗證內容

XmlValueGetter delegate可用來將屬性、文字或空格符節點的值傳遞為與屬性、文字或空格符節點之 XML 架構定義語言 (XSD) 類型相容的 Common Language Runtime (CLR) 類型。 XmlValueGetter delegate 很有用,當屬性、文字或空白符節點的 CLR 值已經可用時,可以避免將其轉換為 string 的成本,然後再重新解析以進行驗證。

ValidateAttributeValidateTextValidateWhitespace 方法會多載並接受屬性、文字或空白元節點的值做為 stringXmlValueGetterdelegate

類別的 XmlSchemaValidator 下列方法接受 XmlValueGetterdelegate 做為參數。

以下是簡介中類別XmlValueGetter範例中取得的範例。delegateXmlSchemaValidator XmlValueGetter delegate 傳回屬性作為 DateTime 物件的值。 若要驗證 傳DateTime回的這個XmlValueGetter物件,XmlSchemaValidator物件會先將它轉換成 ValueType (ValueType 是 XSD 型別的預設 CLR 對應),以取得屬性的數據類型,然後檢查已轉換值的 Facet。

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);
}

如需 的完整範例 XmlValueGetterdelegate,請參閱簡介中的範例。 如需有關 XmlValueGetterdelegate 的更多資訊,請參閱 XmlValueGetterXmlSchemaValidator 類別參考文件。

架構後Validation-Information

類別 XmlSchemaInfo 代表由類別 XmlSchemaValidator 驗證的 XML 節點的一部分後架構Validation-Information。 類別的各種方法會接受XmlSchemaValidator 物件作為XmlSchemaInfo 的選擇性(nullout 參數。

成功驗證時,對象的屬性 XmlSchemaInfo 會以驗證的結果來設定。 例如,在使用 ValidateAttribute 方法成功驗證屬性時, XmlSchemaInfo 物件的 (如果指定) SchemaAttributeSchemaTypeMemberTypeValidity 屬性會以驗證的結果來設定。

下列 XmlSchemaValidator 類別方法接受 XmlSchemaInfo 物件做為 out 參數。

如需 類別的完整範例 XmlSchemaInfo ,請參閱簡介中的範例。 如需 類別 XmlSchemaInfo 的詳細資訊,請參閱 XmlSchemaInfo 類別參考檔。

擷取預期的粒子、屬性和未指定的默認屬性

類別 XmlSchemaValidator 會提供 GetExpectedAttributesGetExpectedParticlesGetUnspecifiedDefaultAttributes 方法,以擷取目前驗證內容中預期的粒子、屬性和未指定的默認屬性。

擷取預期中的粒子

方法 GetExpectedParticles 會傳回物件陣列 XmlSchemaParticle ,其中包含目前專案內容中預期的粒子。 方法可以傳回的有效粒子是 GetExpectedParticlesXmlSchemaElement 類別的實例。

當內容模型的撰寫器是 xs:sequence時,只會傳回序列中的下一個粒子。 如果內容模型的合成器是 xs:allxs:choice,則會傳回在目前元素上下文中可出現的所有有效元件。

備註

如果在呼叫GetExpectedParticles方法之後立即呼叫Initialize方法,GetExpectedParticles方法會傳回所有全域元素。

例如,在以下的 XML 架構定義語言 (XSD) 架構與 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 類別的 GetExpectedAttributesAddSchemaXmlSchemaValidator 方法的結果依賴於正在驗證的當前上下文。 如需詳細資訊,請參閱本主題中的「驗證內容」一節。

如需 方法的 GetExpectedParticles 範例,請參閱簡介中的範例。 如需有關 GetExpectedParticles 方法的詳細資訊,請參閱 XmlSchemaValidator 類別參考文件。

提取預期的屬性

方法 GetExpectedAttributes 會傳回物件的陣列 XmlSchemaAttribute ,其中包含目前專案內容中預期的屬性。

例如,在簡介的範例中,會使用 GetExpectedAttributes 方法來擷取 book 元素的所有屬性。

如果您在呼叫GetExpectedAttributes方法後立即呼叫ValidateElement方法,則會返回 XML 文件中可能出現的所有屬性。 不過,如果您在呼叫了一次或多次 GetExpectedAttributes 方法之後,再呼叫 ValidateAttribute 方法,則會傳回尚未驗證目前元素的屬性。

備註

GetExpectedParticles 類別的 GetExpectedAttributesAddSchemaXmlSchemaValidator 方法的結果依賴於正在驗證的當前上下文。 如需詳細資訊,請參閱本主題中的「驗證內容」一節。

如需 方法的 GetExpectedAttributes 範例,請參閱簡介中的範例。 如需有關 GetExpectedAttributes 方法的詳細資訊,請參閱 XmlSchemaValidator 類別參考文件。

擷取未指定的預設屬性

使用 GetUnspecifiedDefaultAttributes 方法填充 ArrayList ,在元素上下文中對任何具有預設值但未經先前使用 XmlSchemaAttribute 方法驗證的屬性,以 ValidateAttribute 物件進行填充。 應該在元素內容中的每個屬性上呼叫GetUnspecifiedDefaultAttributes方法之後,再呼叫ValidateAttribute方法。 GetUnspecifiedDefaultAttributes方法應該用來判斷要插入 XML 檔中要驗證的預設屬性。

如需有關 GetUnspecifiedDefaultAttributes 方法的詳細資訊,請參閱 XmlSchemaValidator 類別參考文件。

處理架構驗證事件

在驗證期間發生的架構驗證警告和錯誤是由ValidationEventHandler類別的XmlSchemaValidator事件處理。

架構驗證警告的值為 XmlSeverityTypeWarning ,而架構驗證錯誤的值為 XmlSeverityTypeError。 如果ValidationEventHandler尚未被指派,則針對所有值為XmlSchemaValidationExceptionXmlSeverityType的架構驗證錯誤擲回Error。 不過, XmlSchemaValidationException 不會針對值為 XmlSeverityTypeWarning的架構驗證警告擲回 。

以下是收到了架構驗證時警告和錯誤的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 ,以及可在每個狀態中進行之方法呼叫的順序和發生次數。

國家 過渡
驗證 InitializeValidateAttribute | TopLevel*) EndValidation
TopLevel ValidateWhitespace | ValidateText |元素
元素 ValidateElement ValidateAttribute* (ValidateEndOfAttributes 內容*)? ValidateEndElement |

ValidateElement ValidateAttribute * SkipToEndElement |

ValidateElement ValidateAttribute * ValidateEndOfAttributes 內容* SkipToEndElement |
內容 ValidateWhitespace | ValidateText |元素

備註

當依據InvalidOperationException物件的當前狀態,以不正確的順序呼叫方法時,上述表格中的每個方法都會擲回一個XmlSchemaValidator

上述狀態轉換表使用標點符號來描述類別 XmlSchemaValidator 狀態轉換中每個狀態可呼叫的方法和其他狀態。 使用的符號與文件類型定義之 XML 標準參考中找到的符號相同。

下表描述上述狀態轉換數據表中找到的標點符號如何影響方法,以及可在 類別狀態轉換 XmlSchemaValidator 中針對每個狀態呼叫的其他狀態。

象徵 說明
| 可以呼叫方法或狀態(列前的方法或之後的狀態)。
? 問號前面的方法或狀態是選擇性的,但如果呼叫它,則只能呼叫一次。
* * 符號前面的方法或狀態是選擇性的,而且可以多次呼叫。

驗證背景

XmlSchemaValidator類別的方法,用來驗證 XML 資訊集中的元素、屬性和內容,會改變XmlSchemaValidator物件的驗證內容。 例如, SkipToEndElement 方法會略過目前專案內容的驗證,並準備 XmlSchemaValidator 對象來驗證父元素內容中的內容;這相當於略過目前專案之所有子系的驗證,然後呼叫 ValidateEndElement 方法。

GetExpectedParticles 類別的 GetExpectedAttributesAddSchemaXmlSchemaValidator 方法的結果依賴於正在驗證的當前上下文。

下表描述在呼叫用來驗證 XML 資訊集中元素、屬性和內容之 XmlSchemaValidator 類別的其中一個方法之後呼叫這些方法的結果。

方法 獲取預期粒子 GetExpectedAttributes AddSchema
Initialize 如果呼叫預設 Initialize 方法, GetExpectedParticles 則傳回包含所有全域元素的陣列。

如果呼叫採用 Initialize 作為參數的多載 XmlSchemaObject 方法以初始化元素的部分驗證,GetExpectedParticles 則只會回傳被 XmlSchemaValidator 物件初始化的元素。
如果呼叫預設 Initialize 方法, GetExpectedAttributes 則會傳回空陣列。

如果呼叫接受Initialize作為參數的XmlSchemaObject方法的多載,以初始化屬性的部分驗證,則GetExpectedAttributes僅返回物件所初始化的XmlSchemaValidator屬性。
如果沒有前置處理錯誤,將架構加入XmlSchemaSet物件的XmlSchemaValidator
ValidateElement 如果內容元素有效,GetExpectedParticles 則會傳回作為內容元素之子元素的預期序列。

如果內容項目無效, GetExpectedParticles 則傳回空陣列。
如果內容專案有效,而且先前未呼叫 ValidateAttributeGetExpectedAttributes 則會傳回內容項目上定義的所有屬性清單。

如果某些屬性已經驗證, 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 所傳回的值。

另請參閱