AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1296&pId=-1
Transform XML into HTML Using XSLT
page
by Haissam Abdul Malak
Feedback
Average Rating: 
Views (Total / Last 10 Days): 38553/ 32

Introduction

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" ?> 
<Persons>
<Person>
<FirstName>Haissam</FirstName>
<LastName>Abdul Malak</LastName>
<JobTitle>System Developer</JobTitle>
<Blog>http://www.dotnetslackers.com/community/blogs/haissam/</Blog>
<Email>haissam50@hotmail.com</Email>
<ImageUrl>Images/haissam.jpg</ImageUrl>
</Person>
<Person>
<FirstName>User1</FirstName>
<LastName>LastName</LastName>
<JobTitle>QA</JobTitle>
<Blog>http://www.microsoft.com </Blog>
<Email>user@hotmail.com</Email>
<ImageUrl>Images/user.jpg</ImageUrl>
</Person>
</Persons>

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">
<html>
<body>
<div id="divContainer" style="width:100%;height:5%">
<b><u><xsl:text>Simple Search Engine:</xsl:text></u></b>
<br/>
<br/>
<INPUT id="SearchCriteria" type="text"/>
<INPUT type="button" value="Search" onclick="Search()"/>
<INPUT id="MoreOptions" type="Button" value="More Options" onclick="DivStatus()"/>
<br/>
<br/>
<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>
</SELECT>
<br/>
<DIV style="width:100px">Sort 
<SELECT id="Sorting">
  <OPTION value="Ascending">Ascending</OPTION>
  <OPTION value="Descending">Descending</OPTION>
</SELECT>
</DIV>
</div>
</div>

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:choose>
<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)">
<table>
<xsl:variable name="BlogUrl">
<xsl:value-of select="Blog"/>
</xsl:variable>
<tr><td><img src="{ImageUrl}" style="width:100px;height:100px"/></td></tr>
<tr><td></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>
<tr><td><xsl:text>Blog:   
 </xsl:text><a href="javascript:OpenWindow('{$BlogUrl}')"><xsl:value-of
 select="Blog"/></a></td></tr>
<tr><td><xsl:text>Email:    </xsl:text><xsl:value-of select="Email"/></td></tr>
</table>
<hr width="50%"/>
</xsl:if>
</xsl:for-each>
</xsl:when>
</xsl:choose>
</body>
</html>
</xsl:template>

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"/>
</xsl:variable>

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 =
  document.getElementById('Sorting').options[sortDropDownIndex].value;
  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)
{
  window.open(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(divlayer.style.display == 'none')
{
divlayer.style.display = 'block';
moreoptionsControl.value = 'Hide Options';
}
else
{
divlayer.style.display = '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.

Conclusion

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!


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 4:47:23 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search