Validation Using a Wrapped XmlReader Object 

You can create a new XmlReader object that is wrapped around another XmlReader object. This allows you to add additional features on top of another XmlReader object. For example, the XmlNodeReader class does not support data validation. By creating an XmlReader object that wraps around the XmlNodeReader object, you can validate the data stored in the XmlNodeReader object.


In the following example, an XML file is loaded into an XML document and modified. The XML document is passed to an XmlNodeReader, which is then passed to the System.Xml.XmlReader.Create method. When the validating reader parses the file, it can validate any changes made to the XML file.

using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;

public class Sample {

  public static void Main() {

    // Create and load the XML document.
    XmlDocument doc = new XmlDocument();

    // Make changes to the document.
    XmlElement book = (XmlElement) doc.DocumentElement.FirstChild;
    book.SetAttribute("publisher", "Worldwide Publishing");

    // Create an XmlNodeReader using the XML document.
    XmlNodeReader nodeReader = new XmlNodeReader(doc);

    // Set the validation settings on the XmlReaderSettings object.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add("urn:bookstore-schema", "books.xsd");
    settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);

   // Create a validating reader that wraps the XmlNodeReader object.
   XmlReader reader = XmlReader.Create(nodeReader, settings);
   // Parse the XML file.
   while (reader.Read());

  // Display any validation errors.
  private static void ValidationCallBack(object sender, ValidationEventArgs e) {
    Console.WriteLine("Validation Error: {0}", e.Message);


The following files are used as input.


<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema">
  <book genre="autobiography">
    <title>The Autobiography of Benjamin Franklin</title>
  <book genre="novel">
    <title>The Confidence Man</title>


<xsd:schema xmlns:xsd=""

 <xsd:element name="bookstore" type="bookstoreType"/>

 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>

 <xsd:complexType name="bookType">
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="authorName"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  <xsd:attribute name="genre" type="xsd:string"/>

 <xsd:complexType name="authorName">
   <xsd:element name="first-name"  type="xsd:string"/>
   <xsd:element name="last-name" type="xsd:string"/>



Validation Error: The 'publisher' attribute is not declared.

See Also