validating a xml file aganist a schema.

An xml file is said to be valid if it is validated successfully against a schema. It is a good practice to n  validate a xml file against a schema before the application starts consuming it. I want to show how to do this programmatically using C#.

Below is the sample xml file and schema file

BookStore.xml:: 

<?xml version="1.0" encoding="utf-8"?>
        <
BookStore >
               <
Book ISBN="1224-43-21-2321">
                        <
title>Oxford Advanced Learners Dictionary</title>
                         <
Authors>
                                   <
AuthorName>David Nutshell</AuthorName>
                        </
Authors>
                        <
Price>530.00</Price>
               </
Book>
               <
Book ISBN="1223-13-45-6581">
                        <
title>C# 3.0 Professional</title>
                        <
Authors>
                                <
AuthorName>Ken Thompson</AuthorName>
                                <
AuthorName>Mark Williams</AuthorName>
                       </
Authors>
                      <
Price>530.00</Price>
              </
Book>
        </
BookStore>

BookStore.xsd::

<?xml version="1.0" encoding="utf-8"?>
<
xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"xmlns:xs="http://www.w3.org/2001/XMLSchema" >
      <
xs:element name="BookStore" >
             <
xs:complexType>
                    <
xs:sequence>
                          <
xs:element maxOccurs="unbounded" name="Book">
                                 <
xs:complexType>
                                        <
xs:sequence>
                                               <
xs:element name="title" type="xs:string" />
                                               <
xs:element name="Authors">
                                                     <
xs:complexType>
                                                            <
xs:sequence>
                                                                   <
xs:element maxOccurs="unbounded" minOccurs="1"name="AuthorName" type="xs:string" />
                                                           </
xs:sequence>
                                                  </
xs:complexType>
                                           </
xs:element>
                                           <
xs:element name="Price" type="xs:decimal" />
                                    </
xs:sequence>
                                    <
xs:attribute name="ISBN" type="xs:string" use="required" />
                              </
xs:complexType>
                      </
xs:element>
              </
xs:sequence>
       </
xs:complexType>
  </
xs:element>
</
xs:schema>

Step by Step procedure to validate a xml file against a schema

Step 1: Add the namespace System.Xml. Create a instance for XmlDocument class.

Step 2: Add the schema file to the XmlDocument instance.

Step 3:  Load the given xml file into the XmlDocument instance.

Step 4: Now call the Validate method on XmlDocument instance passing the validateEventHandler event. If any xml element is not configured as per the schema rule then this event will be fired, assigning a severity to the violation.
 
Below is the code for this:

class xmlValidate
    {
        
public static bool validXml = true;
        
static void Main(string[] args)
        {           
            // step-1 
            
XmlDocument XmlDoc = new XmlDocument();
            // step-2
            XmlDoc.Schemas.Add(
null, @"c:\BookStore.xsd");
            // step-3
            XmlDoc.Load(@
"c:\BookStore.Xml");
            // step-4           
            XmlDoc.Validate(
newSystem.Xml.Schema.ValidationEventHandler(xrs_ValidationEventHandler));
            
if(validXml == true)
                
Console.WriteLine("valid xml file");
            
else
                
Console.WriteLine("not a valid xml file");
         // clearing the flag
            validXml= true;
        }
        
static void xrs_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)
        {
            
if (e.Severity == System.Xml.Schema.XmlSeverityType.Error)
                validXml = 
false;           
        }
    }

Explanation:
 
Open a C# console application. Open the Program.cs file and delete the Program class and copy the above code. Add the name space System.Xml. and also create the above xml and schema files in C:\ drive.  Compile the above code and run the application.
 
Testing:
 
Case1: The above given xml is valid so “valid xml file” will be displayed on the screen
Case2: now remove the attribute ISBN on any book element from the BookStore.xml and run again. A “not a valid xml file ” will be displayed.

Ebook Download
View all
Learn
View all