共用方式為


XmlValidatingReader 驗證事件處理常式回呼

ValidationEventHandler 事件可用來設定事件處理常式,以便接收文件類型定義 (DTD)、XML 資料精簡 (XDR) 及 XML 結構描述定義語言 (XSD) 結構描述驗證錯誤的相關資訊。

透過 ValidationEventHandler 回呼,可以報告驗證錯誤和警告。 如果未提供 ValidationEventHandler 且發生剖析錯誤,則會引發 XmlException 而報告錯誤。 如果發生驗證錯誤,則會擲回 XmlSchemaException。 如果擲回例外狀況,則無法重新啟動 XmlValidatingReader

注意事項注意事項

XmlValidatingReader 類別在 .NET Framework 2.0 版 中已過時。您可以使用 XmlReaderSettings 類別和 Create 方法,來建立驗證 XmlReader 執行個體。如需詳細資訊,請參閱使用 XmlReader 驗證 XML 資料

使用 ValidationEventHandler

只有在 ValidationType 屬性設為 ValidationType.DTD、ValidationType.Schema、ValidationType.XDR 或 ValidationType.Auto 的情況下,才會發生具有 ValidationEventHandler 的驗證事件。 ValidationType 屬性預設是設為 ValidationType.Auto。

將 XML 結構描述和 XDR 結構描述加入至 XmlSchemaCollection 時,XmlSchemaCollection 類別會使用 ValidationEventHandler 事件來處理這些結構描述中的驗證錯誤。

下列程式碼範例示範提供驗證事件處理常式時的 ValidationCallback 方法。

Sub ValidationCallback(sender As Object, args As ValidationEventArgs)
End Sub
void ValidationCallback(object sender, ValidationEventArgs e)
{
}

ValidationEventArgs 類別對於文字訊息、用以指出驗證錯誤或警告的 XmlSeverityType 列舉型別,以及含有特定驗證錯誤之相關 XmlSchemaException 資訊的例外狀況,都具有相關的屬性。

如果未提供事件處理常式,則會對第一個具有 XmlSeverityType = Error 的驗證錯誤擲回例外狀況。 發生此錯誤後,即無法重新啟動 XmlValidatingReader。 含有 XmlSeverityType = Warning 的驗證錯誤不會引發例外狀況。 如果在依據結構描述或 DTD 進行驗證時發生驗證錯誤,則會擲回 XmlSchemaException

如果因為內容模型不相符而使得所指定項目或屬性透過 ValidationCallback 方法報告有效性錯誤,則不會驗證該項目之內容模型的其他部份。 (不過會驗證指定項目或屬性的項目子系)。在 XmlValidatingReader 識別所指定項目的錯誤後,它就會停止該項目的驗證。

檢查驗證結果

ValidationEventHandler 事件和 XmlSeverityType 列舉型別可用來驗證 XML 執行個體文件的驗證狀態。 針對嚴重驗證錯誤,ValidationEventArgs.Severity 屬性的值為 XmlSeverityType.Error 時,表示已發生嚴重錯誤。 針對所有非嚴重驗證錯誤 (例如,因為沒有結構描述或 DTD 資訊可用於驗證項目和屬性而傳回的錯誤),Severity 屬性的值為 XmlSeverityType.Warning。 所有的 ValidationType 值都可能產生警告,但 ValidationType.None 除外。

注意事項注意事項

不支援呼叫變更 ValidationEventHandler 內之讀取器狀態的任何方法。針對執行個體,我們無法保證您在事件處理常式中的讀取器上呼叫 Read() 時 (無論以隱含或明確的方式),讀取器的狀態會產生什麼變化。

下列程式碼範例顯示如何使用 ValidationEventHandler 事件,在 XmlSchemaCollection 中,依據 XML 結構描述來驗證 XML 執行個體文件。

Private Shared reader As XmlValidatingReader = Nothing
Private Shared treader As XmlTextReader = Nothing
Private Shared filename As [String] = String.Empty
   
   Public Overloads Shared Sub Main()

      Dim xsc As New XmlSchemaCollection()
      
      Try
         xsc.Add(Nothing, New XmlTextReader("MySchema.xsd"))
         treader = New XmlTextReader("Myfilename.xml")
         reader = New XmlValidatingReader(treader)
         
         reader.Schemas.Add(xsc)
         reader.ValidationType = ValidationType.Schema
         

         AddHandler reader.ValidationEventHandler, AddressOf sample.ValidationCallback
         
         While reader.Read()
         End While
      Catch e As Exception
         If Not (reader Is Nothing) Then
            reader.Close()
         End If
         Console.WriteLine(e.ToString())
      End Try
   End Sub
   ' Main
   
Shared Sub ValidationCallback(sender As Object, args As ValidationEventArgs)
      If args.Severity = XmlSeverityType.Warning Then
         Console.WriteLine("No schema found to enforce validation.")
         Console.WriteLine((filename + "(" + treader.LineNumber + "," + treader.LinePosition + ")" + args.Message))
      End If
' ValidationCallback
End Sub
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Sample
{
    static String filename = "BooksSchema.xml";
    static XmlTextReader treader = null;

    public static void Main()
    {

        XmlValidatingReader reader = null;
        
        XmlSchemaCollection xsc = new XmlSchemaCollection();
        ValidationEventHandler eventHandler = new ValidationEventHandler(Sample.ValidationCallback);

        try
        {
            xsc.Add(null, new XmlTextReader("Books.xsd"));
            treader = new XmlTextReader(filename);
            reader = new XmlValidatingReader(treader);

            reader.Schemas.Add(xsc);
            reader.ValidationType = ValidationType.Schema;

            reader.ValidationEventHandler += eventHandler;

            while (reader.Read())
            {
            }

            Console.WriteLine("Validation successful.");
        } 
        catch (Exception e)
        {
            if ( reader != null )
                reader.Close();
            Console.WriteLine(e.ToString());
        }

    }

    public static void ValidationCallback(object sender, ValidationEventArgs args )
    {
        if (args.Severity == XmlSeverityType.Warning)
        {
            Console.WriteLine("No schema found to enforce validation.");
            Console.WriteLine(filename + "(" + treader.LineNumber + "," + treader.LinePosition + ")" + args.Message);

        }
    }
}

以下描述要驗證的輸入檔 BooksSchema.xml 的內容。

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema">
  <book genre="autobiography">
    <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">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

以下描述要驗證的輸入檔 Books.xsd 的內容。

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">

 <xs:element name="bookstore" type="bookstoreType"/>

 <xs:complexType name="bookstoreType">
  <xs:sequence maxOccurs="unbounded">
   <xs:element name="book"  type="bookType"/>
  </xs:sequence>
 </xs:complexType>

 <xs:complexType name="bookType">
  <xs:sequence>
   <xs:element name="title" type="xs:string"/>
   <xs:element name="author" type="authorName"/>
   <xs:element name="price"  type="xs:decimal"/>
  </xs:sequence>
  <xs:attribute name="genre" type="xs:string"/>
 </xs:complexType>

 <xs:complexType name="authorName">
  <xs:sequence>
   <xs:element name="first-name"  type="xs:string"/>
   <xs:element name="last-name" type="xs:string"/>
  </xs:sequence>
 </xs:complexType>

</xs:schema>

下列程式碼範例顯示如何使用 ValidationEventHandler 事件。 任何錯誤都會寫入主控台。

' Set the validation event handler.
AddHandler reader.ValidationEventHandler, AddressOf ValidationCallBack


Private Sub ValidationCallBack(sender As Object, args As ValidationEventArgs)
   Console.WriteLine("Validation CallBack: type: {0} message: {1}", args.Severity, args.Message)
' ValidationCallBack
End Sub
// Set the validation event handler.
reader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

private void ValidationCallBack(object sender, ValidationEventArgs args )
{
  Console.WriteLine("Validation CallBack: type: {0} message: {1}", args.Severity, args.Message);
}

請參閱

概念

使用 XmlReader 讀取 XML

其他資源

使用 XmlReader 類別