Export (0) Print
Expand All

XmlValidatingReader.ValidationEventHandler Event

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

Namespace: System.Xml
Assembly: System.Xml (in system.xml.dll)

public event ValidationEventHandler ValidationEventHandler
/** @event */
public void add_ValidationEventHandler (ValidationEventHandler value)

/** @event */
public void remove_ValidationEventHandler (ValidationEventHandler value)

JScript supports the use of events, but not the declaration of new ones.

NoteNote

The XmlValidatingReader class is obsolete in Microsoft .NET Framework version 2.0. You can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. For more information, see Validating XML Data with XmlReader.

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).

NoteNote

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.

The following example validates a file against an XML Schema.

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 );
  }
}

import System.*;
import System.IO.*;
import System.Xml.*;
import System.Xml.Schema.*;

public class Sample
{
    private XmlTextReader txtReader = null;
    private XmlValidatingReader reader = null;
    private boolean mSuccess = true;

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

    public static void main(String[] args)
    {
        Sample validation =  new Sample();
    } //main

    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.add_ValidationEventHandler(new ValidationEventHandler
                (this.ValidationEventHandle));

            // Read XML data
            while(reader.Read()) {

            }
            Console.WriteLine("Validation finished. Validation {0}",
                (mSuccess == true) ? "successful" : "failed");
        }
        finally {
            //Close the reader.
            if (reader != null) {
                reader.Close();
            }
        }
    } //Validate

    //Display the validation error.
    private void ValidationEventHandle(Object sender, ValidationEventArgs args) 
    {
        mSuccess = false;
        Console.WriteLine(("\r\n\tValidation error: " + args.get_Message()));
    } //ValidationEventHandle
} //Sample

The sample uses the following two input files:

notValidXSD.xml (The xsi:schemaLocation attribute identifies the XML Schema 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>

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>

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft