XmlValidatingReader.ValidationEventHandler 事件

定义

设置事件处理程序以接收有关文档类型定义 (DTD)、XML 数据简化 (XDR) 架构和 XML 架构定义语言 (XSD) 架构验证错误的信息。

public:
 event System::Xml::Schema::ValidationEventHandler ^ ValidationEventHandler;
public event System.Xml.Schema.ValidationEventHandler ValidationEventHandler;
member this.ValidationEventHandler : System.Xml.Schema.ValidationEventHandler 

事件类型

ValidationEventHandler

示例

以下示例针对 XML 架构验证文件。

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Xml::Schema;
public ref class Sample
{
private:
   XmlTextReader^ txtreader;
   XmlValidatingReader^ reader;
   Boolean m_success;

public:
   Sample()
   {
      txtreader = nullptr;
      reader = nullptr;
      m_success = true;
      
      //Validate file against the XSD schema. 
      //The validation should fail.
      Validate( "notValidXSD.xml" );
   }


private:
   void Validate( String^ filename )
   {
      try
      {
         Console::WriteLine( "Validating XML file {0}", filename );
         txtreader = gcnew XmlTextReader( filename );
         reader = gcnew XmlValidatingReader( txtreader );
         
         // Set the validation event handler
         reader->ValidationEventHandler += gcnew ValidationEventHandler( this, &Sample::ValidationEventHandle );
         
         // Read XML data
         while ( reader->Read() )
         {}
         Console::WriteLine( "Validation finished. Validation {0}", (m_success == true ? (String^)"successful" : "failed") );
      }
      finally
      {
         
         //Close the reader.
         if ( reader != nullptr )
                  reader->Close();
      }

   }


   //Display the validation error.
   void ValidationEventHandle( Object^ /*sender*/, ValidationEventArgs^ args )
   {
      m_success = false;
      Console::WriteLine( "\r\n\tValidation error: {0}", args->Message );
   }

};

int main()
{
   gcnew Sample;
}

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

public class Sample
{

  private XmlTextReader txtreader = null;
  private XmlValidatingReader reader = null;
  private Boolean m_success = true;

  public Sample ()
  {
        //Validate file against the XSD schema.
        //The validation should fail.
        Validate("notValidXSD.xml");
  }

  public static void Main ()
  {
      Sample validation = new Sample();
  }

  private void Validate(String filename)
  {
     try
     {
        Console.WriteLine("Validating XML file " + filename.ToString());
        txtreader = new XmlTextReader (filename);
        reader = new XmlValidatingReader (txtreader);

        // Set the validation event handler
        reader.ValidationEventHandler += new ValidationEventHandler (this.ValidationEventHandle);

        // Read XML data
        while (reader.Read()){}
        Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful" : "failed"));
     }

     finally
     {
        //Close the reader.
        if (reader != null)
          reader.Close();
     }
  }

  //Display the validation error.
  private void ValidationEventHandle (object sender, ValidationEventArgs args)
  {
     m_success = false;
     Console.WriteLine("\r\n\tValidation error: " + args.Message );
  }
}
Imports System.IO
Imports System.Xml
Imports System.Xml.Schema

Public Class Sample
    
    Private txtreader As XmlTextReader = Nothing
    Private reader As XmlValidatingReader = Nothing
    Private m_success As Boolean = True
    
    Public Sub New()
        'Validate file against the XSD schema. 
        'The validation should fail.
        Validate("notValidXSD.xml")
    End Sub
    
    Public Shared Sub Main()
        Dim validation As New Sample()
    End Sub
    
    Private Sub Validate(filename As String)
        Try
            Console.WriteLine("Validating XML file " & filename.ToString())
            txtreader = New XmlTextReader(filename)
            reader = New XmlValidatingReader(txtreader)
            
            ' Set the validation event handler
            AddHandler reader.ValidationEventHandler, AddressOf Me.ValidationEventHandle
            
            ' Read XML data
            While reader.Read()
            End While
            Console.WriteLine("Validation finished. Validation {0}", IIf(m_success, "successful", "failed"))
        
        Finally
            'Close the reader.
            If Not (reader Is Nothing) Then
                reader.Close()
            End If
        End Try
    End Sub
     
    'Display the validation error.
    Private Sub ValidationEventHandle(sender As Object, args As ValidationEventArgs)
        m_success = False
        Console.WriteLine(ControlChars.CrLf & ControlChars.Tab & "Validation error: " & args.Message)
    End Sub
End Class

此示例使用以下两个输入文件:

notValidXSD.xml (属性 xsi:schemaLocation 标识 reader.) 的 XML 架构


<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="urn:bookstore-schema books.xsd">
  <book>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
  </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


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

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

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

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

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

</xsd:schema>

注解

备注

XmlValidatingReader在 .NET Framework 2.0 中已过时。 可以使用类和Create方法创建验证XmlReader实例XmlReaderSettings。 有关详细信息,请参阅 XmlReader 引用页的“备注”部分。

仅当指定 DTD、XDR、架构或自动时ValidationType,才会发生Read这些事件。

如果未提供事件处理程序,则会在第一个验证错误上引发一个 XmlException , (严重性等于 XmlSeverityType.Error) 。

备注

如果元素报告验证错误,则不会验证该元素的其余内容模型,但会验证其子级。 读取器仅报告给定元素的第一个错误。

回调处理程序可以使用 ValidationEventArgs.Severity 该属性来保证针对架构验证 XML 实例文档。 该 Severity 属性允许区分验证错误 (严重性等于指示致命错误的 XmlSeverityType.Error) ,并且验证警告 (严重性等于指示没有可用的架构信息的 XmlSeverityType.Warning) 。

适用于

另请参阅