Home > Articles > Web Services > XML

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

The XmlValidatingReader Class

The XmlValidatingReader class is used to validate an XML file against a DTD or a schema (either XDR or XSD). This class is used in conjunction with the XmlTextReader class and provides the same access to the document contents. The properties and methods of these two classes are essentially identical. The differences between them lie in two properties of the XmlValidatingReader class that are related to validation.

The ValidationType property specifies the type of validation to be performed. The possible settings for this property are the ValidationType constants described in Table 13.4.

Table 13.4 ValidationType Constants for the ValidationType Property

Constant

Description

Auto

Validates using information contained in the XML document (a DTD defined in a DOCTYPE element, a "schemalocation" attribute, or an inline schema). If no validation information is found, it acts as a nonvalidating parser.

DTD

Validate against a DTD.

None

Does not validate.

Schema

Validate against an XSD Schema.

XDR

Validate against an XDR Schema.


The ValidationEventHandler property is used to inform the XML reader of the event procedure you have created to handle validation errors. This event procedure takes the following form:

public void ValidationCallBack(object sender, ValidationEventArgs args)
// Code to handle error goes here.
}

The name of the procedure can be anything you like. When a validation error occurs, the procedure is called by the XML reader with information about the error contained in the args argument. Use args.ErrorCode and args.Message to obtain a numerical code and text description of the error, respectively. You can also use the LineNumber and LinePosition properties of the XMLTextReader class to get information about the location of the error in the XML file.

To inform the XmlValidatingReader object of your event handler, use the following syntax (assuming that "vrdr" is an instance of the class):

  vrdr.ValidationEventHandler += 
      new ValidationEventHandler( NameOfEventHandler );

Note that you do not have to specify a handler for validation errors. If you do not, the reader will throw an exception when a validation error occurs. The advantage of using a validation error handler is that multiple validation errors can be detected and reported during a single pass over the XML file.

The general procedure for using the XmlValidatingReader class to validate an XML document is as follows. This assumes that the XML file contains the DTD/schema to be used for validation, either inline or as a reference.

  1. Create an instance of the XmlTextReader class and load the XML file into it.

  2. Create an instance of the XmlValidatingReader class and pass it a reference to the XmlTextReader class created in step 1.

  3. Create an event handler procedure to handle validation errors. Code in this procedure can display messages to the user, set flags, or perform other actions as required by the program.

  4. Set the XmlValidatingReader object's ValidationType and ValidationEventHandler properties.

  5. Call the XmlValidatingReader object's Read() method repeatedly until the end of the XML file is reached.

The program in Listing 13.2 shows an example of how to do these tasks. This is a console, or command-line, application written in C# (a console application runs in a "DOS box"). Passed the name of an XML file as a command-line argument, the program validates the file against the DTD or schema information contained or referenced in the file. If the validation is successful, a message to that effect is displayed. If there is a validation error, or an exception is thrown, the relevant information is displayed to the user.

Listing 13.2 C# Program to Demonstrate the XmlValidatingReader Class

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
public class ValidateXML
 {
 private XmlTextReader rdr = null;
 private XmlValidatingReader vrdr = null;
 private Boolean succeeded = true;
 public ValidateXML(string filename)
 // This method performs the validation.
  {
   try
   {
    //Create an XmlTextReader.
    rdr = new XmlTextReader( filename );
    // Create an XmlValidatingReader.
    vrdr = new XmlValidatingReader( rdr );
    // Set validation type to DTD.
    vrdr.ValidationType=ValidationType.DTD;
    // Set the validation callback method.
    vrdr.ValidationEventHandler += 
      new ValidationEventHandler( ValidationCallBack );
    // Read the XML document.
    while (vrdr.Read()) {}
    // Display success or failure message.
    if (succeeded) 
      Console.WriteLine("Validation succeeded.");
    else
      Console.WriteLine("Validation failed.");
   }
   catch (Exception e)
   {
    Console.WriteLine( "Xml Exception: " + e.ToString() );
   }
   finally 
   {
    if ( rdr != null )
     rdr.Close();
    if ( vrdr != null )
     vrdr.Close();
    }
  }
public static void Main(string[] args)
 {
 // Execution starts here.
 // The class reference.
  ValidateXML validate;
 // Ensure that 1 command line argument (the XML file name) was passed.
  if (args.Length != 1)
   Console.WriteLine("Usage: validate xmlfilename");
  else
   validate = new ValidateXML(args[0]);
 }
public void ValidationCallBack( object sender, ValidationEventArgs args )
 {
 // This callback method is called when a validation error occurs.
  succeeded = false;
  // Display error information to the user.
  Console.Write( "\r\n\tValidation error: " + args.Message );
  if ( rdr.LineNumber > 0 )
   Console.WriteLine( "Line: " + rdr.LineNumber + " Position: " + 
    rdr.LinePosition );
 }
}
  • + Share This
  • 🔖 Save To Your Account