Validating an XML Document Programmatically

Introduction

To validate a XML document I have used XmlReader. It can validate an XML document as it reads and parses the document. In this example, we demonstrate how to activate such validation. The illustration validates an XML document that the user chooses, either catalog.xml or catelog1.xml against the XML Schema document catalog.xsd.

You need one schema and two XML files to validate against the schema. This program validates the XML document catalog.xml against the catalog.xsd schema successfully. However, when the user selects the XML document catalog1.xml, validation fails for the book element in the lines containing more than one title element. When the program encounters the invalid node, the method ValidationError is called that displays a message explaining why validation failed.

Catalog

Schema File (Catelog.xsd):

<?xml version="1.0" encoding="utf-8" ?>

<schema xmlns = "http://www.w3.org/2001/XMLSchema"

      =""       ="" xmlns:deitel = "http://www.deitel.com/booklist"

             ="" targetNamespace = "http://www.deitel.com/booklist">

         <element name = "books" type = "deitel:BooksType"/>

         <complexType name = "BooksType">

           <sequence>

                    minOccurs = "1" maxOccurs = "unbounded"/>            

    </sequence>          

  </complexType>

         <complexType name = "SingleBookType">

          <sequence>

                 <element name = "title" type = "string"/>                

    </sequence>     

  </complexType>

</schema>


XML file that conform to the XML Schema document

<?xml version="1.0" encoding="utf-8" ?>

<deitel:books xmlns:deitel = "http://www.deitel.com/booklist">

   <book>

         <title>Visual Basic 2005 How to Program, 3/e</title>     

  </book> 

   <book>

         <title>Visual C# 2005 How to Program</title>      

  </book> 

  <book>

         <title>Java How to Program, 6/e</title>      

  </book> 

     <book>

          <title>C++ How to Program, 5/e</title>      

  </book> 

  <book>

         <title>Internet and World Wide Web How to Program, 3/e</title>     

  </book>

</deitel:books>

XML file that does not conform to the XML Schema document
 

<?xml version="1.0" encoding="utf-8" ?>

<deitel:books xmlns:deitel = "http://www.deitel.com/booklist">

    <book>

        <title>Visual Basic 2012 How to Program, 3/e</title>     

  </book>

    <book>

        <title>Visual C# 2012 How to Program</title>     

  </book>

    <book>

        <title>Java How to Program, 6/e</title>     

  </book>

    <book>

        <title>C++ How to Program, 5/e</title>

        <title>Internet and World Wide Web How to Program, 3/e</title>     

  </book>

    <book>

        <title>XML How to Program</title>     

  </book>

</deitel:books>

Create the XmlSchemaSet variable schemas. An object of the class XmlSchemaSet stores a collection of schemas that an XmlReader can be validated against. It assigns a new XmlSchemaSet object to variable schemas, and calls this object's Add method to add a schema to the collection. The Add method receives as arguments a namespace URI that identifies the schema (http://www.deitel.com/booklist) and the name and location of the schema file (catelog.xsd in the current directory).

private XmlSchemaSet schemas;

schemas = new XmlSchemaSet();

schemas.Add("http://www.deitel.com/booklist", "D:\\Projects\\MyRND in WPF\\MyRND in WPF\\catelog.xsd");
 
Create and set the properties of an XmlReaderSettings object. Set the XmlReaderSettings object's ValidationType property to the value ValidationType.Schema, indicating that we want the XmlReader to perform validation with a schema as it reads an XML document. Again set the XmlReaderSettings object's Schemas property to schemas. This property sets the schema(s) used to validate the document read by the XmlReader.
 

XmlReaderSettings settings = new XmlReaderSettings();

settings.ValidationType = ValidationType.Schema;

settings.Schemas = schemas;

                                   
Register the method ValidationError with the settings object's ValidationEventHandler. The ValidationError method is called if the document being read is found to be invalid or an error occurs (for example, the document cannot be found). Failure to register a method with ValidationEventHandler causes an exception (XmlException) to be thrown when the XML document is found to be invalid or missing.

settings.ValidationEventHandler += ValidationError;

private void ValidationError( object sender ,

ValidationEventArgs arguments )

{

      txtMessage.Text = arguments.Message;

      valid = false; // validation failed

 }
 
After setting the ValidationType property, the Schema's property and ValidationEventHandler of the XmlReaderSettings object, we are ready to create a validating XmlReader. Create an XmlReader that reads the file selected by the user from the txtfilename TextBox and validates it against the catalog.xsd schema by calling the read method inside a whileloop.
 

XmlReader reader =XmlReader.Create( txtFileName.Text, settings );

 while ( reader.Read() );

 if ( valid )

 {

      txtMessage.Text = "Document is valid";

 }  // end if

      valid = true;

      reader.Close();

}

Code
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

using System.Xml.Schema;

using System.Xml;

 

namespace MyRND_in_WPF

{

    /// <summary>

    /// Interaction logic for ValidationXMLScema.xaml

    /// </summary>

    public partial class ValidationXMLScema : Window

    {

        private XmlSchemaSet schemas; // schemas to validate against

        private bool valid = true; // validation result

 

        public ValidationXMLScema()

        {

            InitializeComponent();

        }

 

        private void btnAdd_Click(object sender, RoutedEventArgs e)

        {

        }

        private void btnValidate_Click(object sender, RoutedEventArgs e)

        {

            schemas = new XmlSchemaSet(); // create the XmlSchemaSet class

            // add the schema to the collection

            schemas.Add("http://www.deitel.com/booklist", "D:\\Projects\\MyRND in WPF\\MyRND in WPF\\catalog.xsd");

            // set the validation settings                      

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ValidationType = ValidationType.Schema;

            settings.Schemas = schemas;

            settings.ValidationEventHandler += ValidationError;

            // create the XmlReader object

            XmlReader reader =

            XmlReader.Create(txtFileName.Text, settings);

            // parse the file

            while (reader.Read()) ; // empty body

            if (valid) // check validation result

            {

                txtMessage.Text = "Document is valid";

            } // end if

            valid = true; // reset variable

            reader.Close(); // close reader stream 

        }

        // event handler for validation error

        private void ValidationError(object sender,

         ValidationEventArgs arguments)

        {

            txtMessage.Text = arguments.Message;

            valid = false; // validation failed

        }

    }

}
 
Output

Validating-an-XML-Document.jpg


Similar Articles