共用方式為


驗證和結構描述物件模型

在結構描述驗證期間,可能發生的兩種例外事件分別為警告和錯誤。當剖析器遇到它無法辨識而因此無法驗證的項目時,就會出現警告。在出現警告之後,剖析器可繼續處理執行個體文件。相反地,錯誤是在剖析器因遇到無效狀況而無法完成其工作時發生。

警告

警告通常在剖析器遇到它找不到結構描述資訊來驗證的項目時發生。

在下列範例中,XmlValidatingReader 會對它無法辨識的項目 (例如 htmlpbrbi 項目) 發出警告。XmlValidatingReader 在遇到這些項目時並不會產生錯誤,因為 any 項目指示 subject 項目可有 XML 文件中任何命名空間且數量不限的標記。

下列 XML 結構描述會描述 Warning.xsd 的內容。

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <xs:element name="content" type="contentType" />
   <xs:complexType name="contentType">
    <xs:sequence>
      <xs:element name="subject" type="subjectType" />
    </xs:sequence>
   </xs:complexType>
   <xs:complexType name="subjectType" >
    <xs:sequence>
     <xs:any namespace="##any" processContents="skip" maxOccurs="unbounded"/>
    </xs:sequence>
   <xs:anyAttribute namespace="##any" processContents="skip" />
 </xs:complexType>
</xs:schema>

以下會描述編譯為 Warning.xsd 的 Warning.xml 的內容。

<?xml version="1.0" ?>
<content xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
    xsi:noNamespaceSchemaLocation="Warning.xsd">
 <subject>
   <html>
   <p>sdfsdf</p>
   <br/>
   <b> bold or <i> italic </i> or strong </b>
   </html>
 </subject>
</content>

錯誤

錯誤是事件的一種,它會導致剖析器無法繼續處理正在驗證的 XML 文件。如果項目在其父項目的內容模型中不是位於正確的位置,就可能發生錯誤。

下列範例會產生錯誤,因為 extension 項目不是 complexType 項目的有效子項目。

<xs:complexType>
 <xs:extension base='xs:decimal'>
   <xs:attribute name='sizing' type='xs:string' />
  </xs:extension>
</xs:complexType" />

處理驗證事件

若要處理錯誤和警告,結構描述物件模型 (SOM) 需要支援使用 ValidationEventHandler 委派,也就是您自己設計的回呼。當驗證期間發生錯誤或警告時,就會呼叫這個回呼。

如果註冊了 ValidationEventHandler,剖析器就能夠捨棄無效的資訊並將錯誤資訊傳遞至 ValidationEventHandler 來從錯誤復原。如果未指定 ValidationEventHandler,處理就會停止而不會從錯誤復原。

當發生驗證錯誤時,ValidationEventHandler 會傳遞 ValidationEventArgs 物件,以及您可用來判斷驗證事件嚴重性的 Severity 屬性。ValidationEventArgs 也有包含錯誤訊息的 Message 屬性,以及包含例外狀況 (如果未指定 ValidationEventHandler 就會被擲回) 的 Exception 屬性。

下表說明錯誤和警告與 ValidationEventHandler 之間的關聯性 (Relationship)。

ValidationEventHandler 無 ValidationEventHandler
警告 如果呼叫 ValidationEventHandler 並將 ValidationEventArgs.Severity (等於 XmlSeverityType.Warning) 傳遞給它,文件的處理就會繼續。 不會擲回例外狀況 (Exception),而且結構描述文件的處理會繼續。
錯誤 如果呼叫 ValidationEventHandler 並將 ValidationEventArgs.Severity (等於 XmlSeverityType.Error) 傳遞給它,文件的處理就會繼續而且會捨棄無效資料。 擲回例外狀況,而且結構描述文件的處理會停止。

下列範例使用 ValidationEventHandler 來處理 XML 結構描述檔案中的驗證錯誤。請注意,即使檔案中有驗證錯誤,還是會驗證整個檔案,而不是一發生錯誤就擲回例外狀況。

Imports System.IO
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.Text

Class ReadWriteSample
 
Public Shared Sub ValidationCallbackOne(sender As Object, args As ValidationEventArgs)
      
      If args.Severity = XmlSeverityType.Warning Then
         Console.Write("WARNING: ")
      Else
         If args.Severity = XmlSeverityType.Error Then
            Console.Write("ERROR: ")
         End If 
      End If
      Console.WriteLine(args.Message) ' Prints the error to the screen.
   End Sub 'ValidationCallbackOne
   
   Public Shared Sub Main()
      
      Try
         
         Dim reader As New XmlTextReader("Bad_example.xsd")
         Dim myschema As XmlSchema = XmlSchema.Read(reader, New ValidationEventHandler(AddressOf ValidationCallbackOne))
         
         myschema.Write(Console.Out)
         Dim file As New FileStream("New.xsd", FileMode.Create, FileAccess.ReadWrite)
         Dim xwriter As New XmlTextWriter(file, New UTF8Encoding())
         xwriter.Formatting = Formatting.Indented
         myschema.Write(xwriter)
      
      Catch e As Exception
         Console.WriteLine(e)
      End Try
   End Sub 'Main 
End Class 'ReadWriteSample
[C#]
using System.IO; 
using System;
using System.Xml;  
using System.Xml.Schema;
using System.Text; 

class ReadWriteSample {
   
public static void ValidationCallbackOne(object sender, ValidationEventArgs args) {

if(args.Severity == XmlSeverityType.Warning)
 Console.Write("WARNING: ");
  else if(args.Severity == XmlSeverityType.Error)
 Console.Write("ERROR: ");

Console.WriteLine(args.Message); // Print the error to the screen.
}

public static void Main() {

   try{ 

   XmlTextReader reader = new XmlTextReader ("Bad_example.xsd");
   XmlSchema myschema = XmlSchema.Read(reader, new        ValidationEventHandler(ValidationCallbackOne)); 

   myschema.Write(Console.Out);
   FileStream file = new FileStream ("New.xsd", FileMode.Create,     FileAccess.ReadWrite);
   XmlTextWriter xwriter = new XmlTextWriter (file, new UTF8Encoding());
   xwriter.Formatting = Formatting.Indented;
   myschema.Write (xwriter);

    }catch(Exception e){
       Console.WriteLine(e);
    }
  }/* Main() */ 
}//ReadWriteSample 

下列 XML 結構描述會描述輸入檔案 Bad_example.xsd 的內容。

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="Play" 
                     targetNamespace="http://tempuri.org/Play.xsd" 
                     elementFormDefault="qualified" 
                     xmlns="http://tempuri.org/Play.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name='myShoeSize'>
 <xs:complexType>
  <xs:extension base='xs:decimal'>
    <xs:attribute name='sizing' type='xs:string' />
    <xs:extension />
   </xs:extension>
 </xs:complexType>
</xs:element>
<player></player>
</xs:schema>

請參閱

XML 結構描述物件模型 (SOM) | 使用結構描述驗證 XML