XmlValidatingReader.ValidationEventHandler Zdarzenie

Definicja

Ustawia procedurę obsługi zdarzeń na potrzeby odbierania informacji na temat definicji typu dokumentu (DTD), schematu XML-Data zmniejszonego (XDR) oraz błędów weryfikacji schematu języka XSD (XML Schema Definition Language).

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

Typ zdarzenia

ValidationEventHandler

Przykłady

Poniższy przykład weryfikuje plik względem schematu 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

W przykładzie użyto następujących dwóch plików wejściowych:

notValidXSD.xml (Atrybut xsi:schemaLocation identyfikuje schemat XML dla czytnika).


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

Uwagi

Uwaga

Klasa XmlValidatingReader jest przestarzała w .NET Framework 2.0. Wystąpienie weryfikacji XmlReader można utworzyć przy użyciu XmlReaderSettings klasy i Create metody . Aby uzyskać więcej informacji, zobacz sekcję Uwagi na stronie referencyjnej XmlReader .

Te zdarzenia występują podczas i tylko wtedy Read , gdy ValidationType określono wartość DTD, XDR, Schema lub Auto.

Jeśli nie podano procedury obsługi zdarzeń, XmlException zostanie zgłoszony pierwszy błąd weryfikacji (ważność jest równa XmlSeverityType.Error).

Uwaga

Jeśli element zgłasza błąd weryfikacji, reszta modelu zawartości dla tego elementu nie jest weryfikowana, jednak jego elementy podrzędne są weryfikowane. Czytelnik zgłasza tylko pierwszy błąd dla danego elementu.

Procedura obsługi wywołania zwrotnego może użyć ValidationEventArgs.Severity właściwości w celu zagwarantowania, że dokument wystąpienia XML jest weryfikowany względem schematu. Właściwość Severity umożliwia odróżnienie błędów walidacji (ważność jest równa XmlSeverityType.Error), które wskazują błąd krytyczny, a ostrzeżenia dotyczące walidacji (ważność jest równa XmlSeverityType.Warning), które wskazują, że żadne informacje o schemacie nie są dostępne.

Dotyczy

Zobacz też