XmlValidatingReader.ValidationEventHandler Událost

Definice

Nastaví obslužnou rutinu události pro příjem informací o definici typu dokumentu (DTD), schématu XML-Data omezeném schématu (XDR) a chybách ověřování schématU XML (XSD).

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

Event Type

ValidationEventHandler

Příklady

Následující příklad ověří soubor ve schématu 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

Ukázka používá následující dva vstupní soubory:

notValidXSD.xml (Atribut xsi:schemaLocation identifikuje schéma XML pro čtenáře.)


<?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>

Poznámky

Poznámka

Třída XmlValidatingReader je zastaralá v rozhraní .NET Framework 2.0. Instanci ověřování XmlReader můžete vytvořit pomocí XmlReaderSettings třídy a Create metody. Další informace najdete v části XmlReader Poznámky na referenční stránce.

K těmto událostem dochází pouze v Read případě, že ValidationType je zadána hodnota DTD, XDR, Schema nebo Auto.

Pokud není zadána žádná obslužná rutina XmlException události, vyvolá se při první chybě ověření (závažnost je rovna XmlSeverityType.Error).

Poznámka

Pokud prvek hlásí chybu ověření, zbytek modelu obsahu pro tento prvek není ověřen, ale jeho podřízené položky jsou ověřeny. Čtenář hlásí pouze první chybu daného prvku.

Obslužná rutina zpětného ValidationEventArgs.Severity volání může pomocí vlastnosti zaručit, že je dokument instance XML ověřen vůči schématu. Vlastnost Severity umožňuje rozlišovat mezi chybami ověření (Závažnost je rovna XmlSeverityType.Error), která značí závažnou chybu, a upozornění ověřování (Závažnost je rovna XmlSeverityType.Warning), která indikují, že nejsou k dispozici žádné informace o schématu.

Platí pro

Viz také