XmlValidatingReader.ValidationEventHandler Evento

Definición

Establece un controlador de eventos para recibir información acerca de los errores de validación de definiciones de tipos de documentos (DTD), del esquema XDR (esquema reducido de datos XML) y del esquema XSD (esquema del lenguaje de definición de esquemas XML).

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

Tipo de evento

ValidationEventHandler

Ejemplos

En el ejemplo siguiente se valida un archivo con un esquema 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

En el ejemplo se usan los dos archivos de entrada siguientes:

notValidXSD.xml (El xsi:schemaLocation atributo identifica el esquema XML para el lector).


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

Comentarios

Nota

La XmlValidatingReader clase está obsoleta en .NET Framework 2.0. Puede crear una instancia de XmlReader validación mediante la XmlReaderSettings clase y el Create método . Para obtener más información, vea la sección Comentarios de la página de referencia de XmlReader.

Estos eventos se producen durante Read y solo si se especifica un ValidationType de DTD, XDR, Schema o Auto.

Si no se proporciona ningún controlador de eventos, se produce un XmlException en el primer error de validación (La gravedad es igual a XmlSeverityType.Error).

Nota

Si un elemento notifica un error de validación, el resto del modelo de contenido de ese elemento no se valida, sin embargo, se validan sus elementos secundarios. El lector solo notifica el primer error de un elemento determinado.

El controlador de devolución de llamada puede usar la ValidationEventArgs.Severity propiedad para garantizar que un documento de instancia XML se valida con un esquema. La Severity propiedad permite distinguir entre los errores de validación (La gravedad es igual a XmlSeverityType.Error) que indican un error irrecuperable y las advertencias de validación (Gravedad es igual a XmlSeverityType.Warning) que indican que no hay información de esquema disponible.

Se aplica a

Consulte también