Transform XML into HTML Using XSLT
Published: 04 Jun 2007
In this article Haissam Abdul Malak examines how to output an HTML page from an XML file using XSLT.
by Haissam Abdul Malak
Average Rating: 
Views (Total / Last 10 Days): 46418/ 67


For demonstration purposes, we will create a simple search engine in which XSLT is used to iterate through the XML file (data retrieved from the database) to display the data based on the user entered criteria. It consists of user information, such as First Name, Last Name, Email, etc. Also we will give the user the ability to search in a specified category and in which order the data should be displayed. This option is hidden by default; a button is used to allow the user to specify more options to his or her search.

Throughout this article we have to complete the following steps.

·         Create an XML document containing users' information.

·         Create an XSL file which will navigate through the XML document.

·         Write code behind to transform the XML into HTML.

XML Document

The data used in this demonstration is retrieved from the database, as you may realize the root element is Persons and for each unique person a node called Person with child nodes to hold specific information.

Listing 1

<?xml version="1.0" encoding="utf-8" ?> 
<LastName>Abdul Malak</LastName>
<JobTitle>System Developer</JobTitle>
<Blog> </Blog>

Figure 1

The above figure shows how the page will be when first loaded.

When the More Options button is clicked, we will display more options allowing the user criteria to be more specific.

Figure 2

XSL Document

In this section we will create the XSL file (SearchEngine.xsl). First we will define 3 parameters.

·         <xsl:param name="pName"/>

·         <xsl:param name="selected"/>

·         <xsl:param name="order"/>

·         The first parameter, pName, is used to store the value entered by the user in the textbox. The second is used to store the index of the selected item in the category dropdown list and the third is used for the sort order specified.

Listing 2

<xsl:template match="Persons">
<div id="divContainer" style="width:100%;height:5%">
<b><u><xsl:text>Simple Search Engine:</xsl:text></u></b>
<INPUT id="SearchCriteria" type="text"/>
<INPUT type="button" value="Search" onclick="Search()"/>
<INPUT id="MoreOptions" type="Button" value="More Options" onclick="DivStatus()"/>
<div id="divMoreOptions" style="display:none;width:100px">Category
<SELECT id="Selection">
  <OPTION value="FirstName">FirstName</OPTION>
  <OPTION value="LastName">LastName</OPTION>
  <OPTION value="JobTitle">JobTitle</OPTION>
  <OPTION value="Blog">Blog</OPTION>
  <OPTION value="Email">Email</OPTION>
<DIV style="width:100px">Sort 
<SELECT id="Sorting">
  <OPTION value="Ascending">Ascending</OPTION>
  <OPTION value="Descending">Descending</OPTION>

The above listing is used to display the controls on the webpage, as you can see the "divMoreOptions" div layer is hidden by default. We used JavaScript to show or hide it. Also JavaScript is used to redirect the page into itself by passing the user entered information using the query string.

Listing 3

<xsl:when test="$pName != ''">
<hr width="100%"/>
<xsl:for-each select="Person">
<xsl:sort select="node()[$selected]" order="{$order}"/>
<xsl:if test="contains(node()[position() = $selected],$pName)">
<xsl:variable name="BlogUrl">
<xsl:value-of select="Blog"/>
<tr><td><img src="{ImageUrl}" style="width:100px;height:100px"/></td></tr>
<tr><td><xsl:text>First Name:    </xsl:text><xsl:value-of select="FirstName"/></td></tr>
<tr><td><xsl:text>Last Name:    </xsl:text><xsl:value-of select="LastName"/></td></tr>
<tr><td><xsl:text>Job Title:    </xsl:text><xsl:value-of select="JobTitle"/></td></tr>
 </xsl:text><a href="javascript:OpenWindow('{$BlogUrl}')"><xsl:value-of
<tr><td><xsl:text>Email:    </xsl:text><xsl:value-of select="Email"/></td></tr>
<hr width="50%"/>

The above listing is used to iterate through the xml file and get the information for specific search criteria. First, we are checking if pName parameter is different than empty string, looping through each Person node, select the sorting order the default value is ascending, check if the selected category contains the search criteria entered by the user, then we will display a table containing 6 rows in which the information is displayed. Note the use of a variable called BlogUrl; this variable will store the blog URL retrieved from the xml file and set it as a hyperlink.

Listing 4

<xsl:sort select="node()[$selected]" order="{$order}"/>

The above listing is the way we specify the sort in XSL. The select attribute will be the category name the user has selected. node()[$selected] is used to get the node value. To access the selected parameter value, you should use the $ sign before the parameter name. So if the selected variable is equal to 1, the select attribute will hold node()[1] which is in this case Haissam or User1. The order attribute will hold "ascending" or "descending" based on the user selection as well.

Listing 5

<xsl:if test="contains(node()[position() = $selected],$pName)">

In the above listing, if the test attribute returns true, it will enter the "if" statement.

contains(node()[position() = $selected],$pName) in this XSL code, we are checking if the selected node value contains the search criteria entered by the user.

Listing 6

<xsl:variable name="BlogUrl">
<xsl:value-of select="Blog"/>

This is how you declare a variable in XSL. In this example the variable is called BlogUrl and it will hold the value of the Blog node. Again, to access its value you need to include the $ sign.

JavaScript Code

We used four JavaScript function embedded in the XSL file. To check how to embed JavaScript inside XSLT, please download the project file.

·         Search()

·         getUrl()

·         OpenWindow(url)

·         DivStatus()

Listing 7

function Search()
  var searchCri = document.getElementById('SearchCriteria').value;
  var dropdownIndex = document.getElementById('Selection').selectedIndex;
  var sortDropDownIndex = document.getElementById('Sorting').selectedIndex;
  var sortDropDownValue =
  var url = getUrl();
  var selectionDropDown = parseInt(dropdownIndex)+1;
  window.location.href = url + '?pName=' + searchCri + '&selected=' +
  selectionDropDown + '&order=' + sortDropDownValue;

The above code is used to get the search criteria entered in the textbox, get which selected item in the category dropdown list and get which selected item is selected in the sort dropdown list control. After we get the data, we will redirect the page to itself by sending pName, selected, sortDropDownValue in the query string to be retrieved in code behind and set their values to the 3 parameters defined at the first of the XSL file.

Listing 8

function getUrl()
  var url = window.location.href;
  urlSplitted = url.split('?');
  return urlSplitted[0];

This function is used each time we want to redirect the page to retrieve just the first url of the page without the query string parameters.

Listing 9

function OpenWindow(url)

The above function is used to open the Blog URL in a new window.

Listing 10

function DivStatus()
var divlayer = document.getElementById('divMoreOptions');
var moreoptionsControl = document.getElementById('MoreOptions');
if( == 'none')
{ = 'block';
moreoptionsControl.value = 'Hide Options';
{ = 'none';
moreoptionsControl.value = 'More Options';

The above function is called each time the user clicks on the More Options button to set the div layer which contains the more specific criteria to enter, to hide or show depending on its previous status and to change the text of the textbox to "Hide options" when the div layer is being displayed.

Code behind (C#)

Now, after we created the XSL file and the XML file, all we need to do is to supply the code to be able to transform the XML file into html at runtime. In the section below, I used a combination of the Xml control located in the toolbox and some C# code to be inserted at page_load event.

First, create a dummy WebForm and drag and drop the xml control in it. Now, in page_load event of your code behind copy the below code.

Listing 11

// Set the Xsl file to the TransformSource property
xmlControl.TransformSource = "SearchEngine.Xsl";
// Set the DocumentSource property to the name of the xml file.
xmlControl.DocumentSource = "SearchEngine.xml";
// Set the value of the variables in the query string to string variables.
string pName = Request.QueryString["pName"];
string selected = Request.QueryString["selected"];
string order = Request.QueryString["order"];
// Check if pName is not null
if (pName != null)
  // Create New instance of the XsltArgumentList Class
  XsltArgumentList arguments = new XsltArgumentList();
  // Add the value of the pName variable defined in the xsl file
  arguments.AddParam("pName""", pName);
  arguments.AddParam("selected", "", selected);
  arguments.AddParam("order", "", order.ToLower());
  // Set the TransformArgumentList property to the arguments already declared.
  xmlControl.TransformArgumentList = arguments;

The Xml Control id is xmlControl. First we are setting two properties, TransformSource to the virtual path of the XSL file and DocumentSource to the virtual path of the XML document.

Both documents in this case exist in the root application folder. Three string variables are declared to hold the values of the user criteria. To assign values to the three XSL parameters defined at the first of the XSL file, we have to use the XsltArgumentList class to add the specified values and then set the xml Control TransformArgumentList property to the XsltArgumentList class instantiated.

Figure 3

The above figure shows how the data retrieved from the XML file will be displayed in the WebForm. As you can see, for each user an image is being displayed and below all his or her specific information.


XSLT is a very powerful language as you saw during the above stages. A simple search engine code was easily implemented. Of course, I will be introducing you to another XSLT function and shed a light to all its capabilities in the future.

Happy Coding!

User Comments

Title: sql server   
Name: rajesh kumar jha
Date: 2011-07-23 8:33:12 AM
this is a very good database for
Title: .net to java   
Name: rajesh jha
Date: 2011-07-23 8:31:35 AM
this is very good site for all proggramer
Title: Hi   
Name: Pavan
Date: 2011-05-04 8:58:55 AM
this is the best site
Title: xml to html   
Name: Saravanan
Date: 2011-02-21 1:42:31 AM
Hi all,

i am currently into module where i need to convert a Indesign layout to a web page, i need to get the same design as html, what is there in the Indesign layout.

Please anyone help me

Title: tes   
Name: trial
Date: 2010-10-06 1:20:11 AM
user friendly
Title: Short Title   
Name: test
Date: 2009-09-17 6:38:43 AM
this is a test for xml to html conversion and i just wana test how it will finally look like in the html version..
This has to happen through xslt transformations and user have the option to search in xml file using this option..
Title: xml document to html document   
Name: Bertrand Gillert
Date: 2009-06-30 1:50:14 PM
Hi! We need to create a HTML preview for translation of a complicated catalog. The source is xml, we even have a .xsl. But the .xsl does not display the pictures (which we also have). The xml contains the product ids, the picture file names correspond to the product id. Is there a way to map the product ids to the file names and display the pictures within the loop?
Title: xml document to html document   
Name: Andy Symonds
Date: 2009-06-03 5:00:27 PM
hi erm im tryin to make an xml document into html document the xml document is a conversation over a months period i tried to open it to read it like the other files (the html files) but it wont let me so can u tell me how i could sort this problem out
Title: Embedding XML/XSL source   
Name: Matt
Date: 2009-04-30 12:20:28 AM
It is possible to embed the xml/xsl sources with in the executable itself. Imagine in your particular example that SearchEngine.Xsl and SearchEngine.xml were propriatary. Could you somehow embed these files as .NET resources or something such that the ultimate user of the .NET executable could not read the content of the xml/xsl files?
Title: Test   
Name: Kani
Date: 2009-03-28 9:04:17 AM
Test for XML to HTML Document
Title: testvipul   
Name: testvipul
Date: 2009-02-06 3:28:47 AM
this is a test for xml to html conversion and i just wana test how it will finally look like in the html version..
This has to happen through xslt transformations and user have the option to search in xml file using this option..
Title: feedback for Haissam Abdul Malak article   
Name: kannan from india
Date: 2008-11-06 1:15:58 AM
i have one question, may be u can help me..
how to add images include in this xslt and convert to html..
Title: how to Write code behind to transform the XML into HTML.   
Name: Jagadeesh
Date: 2008-05-29 5:35:47 AM
How to write code to convert from xml to html
Title: Article is very good but Not working for me.   
Name: Sushil Dhanuka
Date: 2008-04-22 8:20:44 AM
Hi Haisaam,

This article is very good but somehow not working for me as I made small changes. I am loading this XSL and XML file directly in HTML using javascript. I do not get any search results.

If you can send me email where I can attach my XSL and HTML files.

It would be very helpful for me.

Thanks in advance

Kind Regards
Title: Good one to know XSLT   
Name: Anjaneya
Date: 2008-02-12 6:55:04 AM
Good Article
Title: Prefix add in URl   
Name: Mukesh
Date: 2007-12-27 4:32:31 AM
how to add the prefix http if it not added by user.
if user write it convert to
Title: Please help on xslt   
Name: Bao
Date: 2007-12-07 4:46:29 AM
Hi Abdul Malak,

I have a question maybe you can help,

Is it possible to read from an HTML form (like the ones that you have on the internet to register to forums, etc) and yo save it into a xml file with XSLT by clicking on a button 'save'?

many thanks for your help !

Title: Very good.   
Name: Jignesh raval
Date: 2007-11-27 7:08:00 AM
I have read your artical, you have explained in such a good manner, very nice and very usefull.

Thank you.

Jignesh Raval, India
Title: Beautiful   
Name: Guido
Date: 2007-07-11 2:26:38 PM
Nice explanation. Hopefully I would be able to change it for my project
Title: Transform XML into HTML Using XSLT   
Name: chanchal choudhary
Date: 2007-06-11 12:46:33 AM
Really good and complete help which satisfies its title completely
Amust read for people who are new to xml transform
Title: Re:Missing Information   
Name: Haissam Abdul Malak
Date: 2007-06-04 11:26:34 AM
check the below link to download the project

Title: Missing Information   
Name: Jim Arthur
Date: 2007-06-04 9:45:25 AM
From your article under Javascript section "To check how to embed JavaScript inside XSLT, please download the project file."
So, where is the download link?
Title: Nice one!   
Name: Bilal Haidar [MVP]
Date: 2007-06-04 9:21:40 AM
Nice article as usual!
I am still waiting for the series ;)


Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2022  |  Page Processed at 2022-01-20 6:31:34 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search