Validate XSL Against XML

Started by dhilipkumar, May 21, 2009, 09:20 PM

previous topic - next topic
Go Down


Validate XSL Against XML

here we shows, how to create a class library for validating a certain XSL file against an XML file. He examines the concept with the help of a series of steps with relevant source code and explanations.

the user is required to provide his or her own XSL file to generate his or her own HTML page based on an XML file we provide. In this situation, the need to verify that the XSL file will display appropriate results and not an empty page is required.

The general steps of this article will be:

1.    Create a Class library project

2.    Create three methods: 1 public and 2 private

3.    Create a property which returns a Hash table containing the invalid Nodes in XSL file

4.    Test the class library

Create a class library project

First, open Visual Studio 2005, click on file/New project and choose Visual C# Class library.

Name the project as XslValidator. Import Two namespaces.

1.    System.Xml

2.    System.Collections

we will write the necessary code for this class library to work. First, we will create 4 fields.

private  XmlDocument xslDoc = null;
private XmlDocument xmlDoc = null;
private bool IsValidTag = false;
public Hashtable htTagValidation = new Hashtable();

here i declared 2 XML documents; one for the XSL file and the other for the XML file.


here i will add the constructor for this class which takes two parameters; the first is the absolute path for the XSL file and the second is the absolute path for the XSL file.

// Load Xsl Document
xslDoc = new XmlDocument();

// Load the Xml Document
xmlDoc = new XmlDocument();

we will create a function called CheckTags which will take a specific node as a parameter.....

This is a recursive function and its goal is to loop through the entire XSL file, get each tag referencing a node in the XML file and check if that tag exists in the XML file.....

originally posted in aspalliance


Finally, we will check if the hash table contains in its value false then we will return false.

This method returns true if no value in the hash table is equal to false which means that the validation passed or false if at least one value in the hash table is equal to false which means that the validation failed

private bool CheckTags(XmlNode currentNode)
  // Loop through all the child nodes of the currentNode
  foreach (XmlNode node in currentNode.ChildNodes)
   // Get the attributes of the currentNode to get the node we need to
   // check its matching in the xml file
    XmlAttributeCollection currentNodeAttributes = node.Attributes;
    if (currentNodeAttributes != null)
      foreach (XmlAttribute currentNodeAttribute in currentNodeAttributes)
        // Checking if the currentNode contains "Page" then we need to compare
        if (currentNodeAttribute.Value.Contains("Page/"))
          // Check its matching
          // if Doesnt match then break directly and return false;
          if (!IsValidTag)
    if (node.Value != null && node.Value.Contains("Page/"))
      // Check if a match exists

      // If no match then break;
      if (IsValidTag == false)

    if (currentNode.ChildNodes.Count > 0)
      // Call this function with the current node
    if (htTagValidation.ContainsValue(false) || htTagValidation.Count == 0)
    // if all the nodes are true it returns true, if 1 node is
    // false then it return false;
    return false;
    return true;

As we are looping through all the tags in the XSL file, we will get all the attributes for a specific tag and again loop through them, once the attribute starts with "Page" (the root node of our XML file), we call another method "CheckNodeInXml"


the CheckNodeInXml takes the tag (retrieved from the XSL) and looping through all the nodes inside the XML file to check if it does not exists and then the IsValidTag variable is set to false.

Finally, each tag in the XSL file will be added to the hash table key and its value will be true if the tag exists in the XML file or false if the tag does not exist.

private void CheckNodeInXml(string nodeToBeChecked)
  // Create a boolean variable with default value "false"
  bool isValid = false;
  // Loop through all the nodes in the xml file
  foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
    // Get for example "Document" from the node to be checked in the
    // xml file from the xslt file
    string[]nodeToBeCheckedSplitted = nodeToBeChecked.Split('/');
    // Check if the node contains this value then it exists
    // and set the boolean variable to true
    if (node.Name.Contains
      (nodeToBeCheckedSplitted[nodeToBeCheckedSplitted.Length - 2]))
      isValid = true;
    // dispose objects
    nodeToBeCheckedSplitted = null;
  IsValidTag = isValid;
  // Set the field isValidTag to the local isValid variable
  htTagValidation.Add(nodeToBeChecked, isValid);

In this case, when we want to display the message for the user containing all the invalid tags all we have to do is to loop through the hash table and check which key value is set to false.

The below listing is a property returning a hash table for the developer to be used if he or she wants to display each invalid tag found in the XSL file for the user.


public Hashtable InvalidTags
    return htTagValidation;

public Boolean Validate()
  return this.CheckTags(xslDoc.DocumentElement);

The above method is a public method which returns a boolean variable retrieved from Checktags method.

After you finish adding all the above code, build the project to compile it into a DLL file found in the bin folder of the current project directory.

we will create a web application project to test our class library. Add a reference to the class library inside your web application by right clicking on the References node in the solution explorer then browse to the class library project bin folder and finally select the xsltValidator.dll file.


<?xml version="1.0"?>
    <Value>Hello World</Value>

Also us the one XSL file (Default.xsl) containing the Listing below.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="">
  <xsl:template match="/">
     <body style="font-family:Verdana;">
       <xsl:value-of select="Page/Document1/Value"/>

We will use the Page_load event of the default.aspx page to apply the validation; simply copy the below code inside this event.

XslValidator validator = new XslValidator(Server.MapPath("~/Default.xsl"),
if (!validator.Validate())
  Hashtable hs = new Hashtable();
  hs = validator.htTagValidation;
  foreach (object s in hs.Keys)
    if (!(bool)hs )
      Response.Write(s.ToString() + " doesnt exist in xml file

I instantiated a new object from XslValidator class and send the absolute path of both XML and XSL file as parameters.
We checked if the validation failed, create a new hash table and set it to the one returned from our class library.

originally posted in aspalliance

Go Up

Quick Reply

With Quick-Reply you can write a post when viewing a topic without loading a new page. You can still use bulletin board code and smileys as you would in a normal post.

Warning: this topic has not been posted in for at least 120 days.
Unless you're sure you want to reply, please consider starting a new topic.

Note: this post will not display until it's been approved by a moderator.
Please leave this box empty:

Type the letters shown in the picture
Listen to the letters / Request another image

Type the letters shown in the picture:

shortcuts: alt+s submit/post or alt+p preview
IT Acumens Web Designing Chennai | GinGly :: Build your Personal Website | CineBuzz :: Cinema News | My Kids Diary :: Kids Memories Writing :: Book Website @ 349 Rs monthly
Copyright 2005 - 2020 :: IT Acumens :: All Rights Reserved. :: Sitemap
ITAcumens Discussion Forum with 2 lakhs post running for 15 years - Powered by IT Acumens Dedicated Server