Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

XmlValidatingReader.ValidationEventHandler Event

Sets an event handler for receiving information about DTD, XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD) schema validation errors.

[Visual Basic]
Public Event ValidationEventHandler As ValidationEventHandler
[C#]
public event ValidationEventHandler ValidationEventHandler;
[C++]
public: __event ValidationEventHandler* ValidationEventHandler;

[JScript] In JScript, you can handle the events defined by a class, but you cannot define your own.

Event Data

The event handler receives an argument of type ValidationEventArgs containing data related to this event. The following ValidationEventArgs properties provide information specific to this event.

Property Description
Exception Gets the XmlSchemaException associated with the validation event.
Message Gets the text description corresponding to the validation event.
Severity Gets the severity of the validation event.

Remarks

These events occur during Read and only if a ValidationType of DTD, XDR, Schema, or Auto is specified.

If no event handler is provided an XmlException is thrown on the first validation error (Severity is equal to XmlSeverityType.Error).

Note   If an element reports a validation error, the rest of the content model for that element is not validated, however, its children are validated. The reader only reports the first error for a given element.

The callback handler can use the ValidationEventArgs.Severity property to guarantee that an XML instance document is validated against a schema. The Severity property allows you to distinguish between validation errors (Severity is equal to XmlSeverityType.Error) that indicate a fatal error, and validation warnings (Severity is equal to XmlSeverityType.Warning) that indicate that no schema information is available.

Example

[Visual Basic, C#, C++] The following example validates a file against an XML Schema (XSD).

[Visual Basic] 
Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.Schema
Imports Microsoft.VisualBasic

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 'New
    
    Public Shared Sub Main()
        Dim validation As New Sample()
    End Sub 'Main
    
    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 'Validate
     
    '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 'ValidationEventHandle
End Class 'Sample

[C#] 
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 );
  }
}

[C++] 
#using <mscorlib.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Xml::Schema;

public __gc class Sample
{
private:
   XmlTextReader* txtreader;
   XmlValidatingReader* reader;
   Boolean m_success;

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

private:
   void Validate(String* filename)
   {    
      try
      {
         Console::WriteLine(S"Validating XML file {0}", filename);
         txtreader = new XmlTextReader (filename);
         reader = new XmlValidatingReader (txtreader);

         // Set the validation event handler
         reader->ValidationEventHandler += new ValidationEventHandler (this, &Sample::ValidationEventHandle);

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

      __finally
      {
         //Close the reader.
         if (reader != 0)
            reader->Close();
      } 
   }

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

int main ()
{
   new Sample();
}

[Visual Basic, C#, C++] The sample uses the following two input files:

[Visual Basic, C#, C++] notValidXSD.xml (The xsi:schemaLocation attribute identifies the XML Schema (XSD) for the reader.)

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

[Visual Basic, C#, C++] 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>

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

XmlValidatingReader Class | XmlValidatingReader Members | System.Xml Namespace | XmlSeverityType

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft