Category Archives: XPATH
XSLT: Apply Templates
Using <xsl:Apply-templates/>
Prerequisit: Please go through previous post “XSLT Startup“
Using apply-templates enable us to use default templates. It also let us not to think about complex XPATH statements/ finding a complex XPATH pattern that works. Though using apply-templates cause your XSLT code to be larger but it let your code to be simple and easy to go through.
I use same example as in “XSLT-startup” post but just used another XSLT:
<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version=”1.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”>
<xsl:template match=”/”>
<html>
<body>
<h1>Employee Listing</h1>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match=”employee”>
<div style=”border: 1px dashed #66CCFF”>
<h3>Employee Id:
<xsl:value-of select=”@employeeid”/>
</h3>
<xsl:apply-templates select=”firstname”/>
<xsl:apply-templates select=”lastname”/>
<xsl:apply-templates select=”homephone”/>
<xsl:apply-templates select=”notes”/>
</div>
</xsl:template>
<xsl:template match=”firstname”>
<b>First Name: </b><xsl:value-of select=”.”/>
<br/>
</xsl:template>
<xsl:template match=”lastname”>
<b>
Last Name: </b> <xsl:value-of select=”.”/>
<br/>
</xsl:template>
<xsl:template match=”homephone”>
<b>
Home Phone:</b> <xsl:value-of select=”.”/>
<br/>
</xsl:template>
<xsl:template match=”notes”>
<b>
Remarks:</b> <xsl:value-of select=”.”/>
<br/>
</xsl:template>
</xsl:stylesheet>
Where XSLT starts with a entry templates where match=”/” and gradually apply templates that matches with the given XPATH statement for each templates.
Please notice that all the Apply-templates tags are within the <xsl:Stylesheet> tag.
Output:

XSLT: StartUp in ASP.NET
XSLT Conversion >> Start Up:
What is XSLT?
XSLT is processors that can convert, manipulate XML files depending on XPATH statement. XSLT is a language that can define style for various XML elements depending on their positions. XSLT self is a hierarchical document. It is also a programming language with a moderate level of keywords and function.
What XSLT can do?
Most of the time we use XSLT to covert XML files to some other format:
- XML to XML
- XML to HTML
- XML to PDF
This post will discuss about converting XSLT using ASP.net.
Steps:
1) Create a VS C# web project.
2) Add a XML document.
3) Add a XSLT document
VS Solution Structure:



Figure 1: VS Solution Structure
Now Let us see some code parts:
The ASPX Page: We will show converted HTML (form XML) as this page data.
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Customer.aspx.cs" Inherits="XsltSolutions._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
</div>
</form>
</body>
</html>
Code Behind:
using System;using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;//need to add
using System.Xml.Xsl;//need to add
namespace XsltSolutions
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ConvertCustomerXml();
}
private void ConvertCustomerXml()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(MapPath(“Customer.xml”));
string xslPath = Server.MapPath(“Customer.xslt”);
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xslPath);
transform.Transform(xmlDoc, null, Response.Output);
}
}
}
Here the ConvertCustomerXml() function is responsible for conversion. Please notice that we are loading a Customer.xml as xml input and also showing the Customer.xslt file. The Transform function is primarily responsible for XML to XSLT transformation. It takes three parameters (the XML, the Output method, and xslt arguments.
XML used in this Example: Customer.XML
<?xml version="1.0" encoding="utf-8" ?><!– This is list of employees –>
<employees>
<employee employeeid=”1″>
<firstname>Nancy</firstname>
<lastname>Davolio</lastname>
<homephone>(206) 555-9857</homephone>
<notes>
<![CDATA[includes a BA in psychology from Colorado State University in 1970.
She also completed "The Art of the Cold Call." Nancy is a member of Toastmasters
International.]]>
</notes>
</employee>
<employee employeeid=”2″>
<firstname>Andrew</firstname>
<lastname>Fuller</lastname>
<homephone>(206) 555-9482</homephone>
<notes>
<![CDATA[Andrew received his BTS commercial in 1974 and a Ph.D. in international
marketing from the University of Dallas in 1981. He is fluent in French and Italian
and reads German. He joined the company as a sales representative, was promoted
to sales manager in January 1992 and to vice president of sales in March 1993.
Andrew is a member of the Sales Management Roundtable, the Seattle Chamber of
Commerce, and the Pacific Rim Importers Association.]]>
</notes>
</employee>
<employee employeeid=”3″>
<firstname>Janet</firstname>
<lastname>Leverling</lastname>
<homephone>(206) 555-3412</homephone>
<notes>
<![CDATA[Janet has a BS degree in chemistry from Boston College (1984).
She has also completed a certificate program in food retailing management.
Janet was hired as a sales associate in 1991 and promoted to sales representative
in February 1992.]]>
</notes>
</employee>
</employees>
XSLT used in this Example: Customer.xslt
<?xml version="1.0" encoding="iso-8859-1"?></xsl:stylesheet>
<xsl:stylesheet version=”1.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”>
<xsl:template match=”/”>
<html>
<body>
<h2>Customer Information</h2>
<table style=”background-color:#97DDFF”>
<tr>
<td>
<table cellspacing =”1px” cellpadding =”2″ style=”background-color:transparent; border:2px solid #00CCFF; font-family:calibri”>
<tr>
<th style=”background-color:#C1FFFF”>
Employee Id
</th>
<xsl:for-each select=”/employees/employee[1]/*”>
<th style=”background-color:#C1FFFF”>
<xsl:value-of select=”name()”/>
</th>
</xsl:for-each>
</tr>
<xsl:for-each select=”/employees/employee”>
<tr>
<td style=”background-color:white”>
<xsl:value-of select=”@employeeid”/>
</td>
<xsl:for-each select=”node()”>
<td style=”background-color:white”>
<xsl:value-of select=”.”/>
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
</table>
</td>
</tr>
</table>
</body>
</html>
</xsl:template>
Output:
Figure 2: XSLT Html Output
Solution Logical Coverage:
1) Naming the Table header using Loop:
Here I placed the table header dynamically form the XML using <xsl:for-each>. Here I have to be concerned about the face that, the table header must be appears only for the first time. Here name() function is returning all the elements names. So, I used the XPATH expression:
<xsl:for-each select="/employees/employee[1]/*">
Here: //employee[1] making sure we are taking the first employee so that the table header elements are only traversing once. So we are getting the following output:

2) Getting row using loop depending on elements:
<xsl:for-each select="/employees/employee">
Here I am traversing all the employee elements and creating a row for each employee elements.
3) Getting field value using loop:
<xsl:for-each select="node()"><td style=”background-color:white”>
<xsl:value-of select=”.”/>
</td>
</xsl:for-each>
Here I am getting all the value of node/elements and resulting in a table data (column).
4) Getting all the Node and Attributes:
<xsl:for-each select="@*|node()"><td style=”background-color:white”>
<xsl:value-of select=”.”/>
</td>
</xsl:for-each>
This will get all the nodes an attributes. No need to get the attributes in a different way than getting all the nodes. In this example we are getting the attributes differently. But there we could use lines this also.
XML Manipulation in XML using XPATH: In a VS2008 project
XML in ASP.NET
This Post will show some startup on XML file manipulation in ASP.net
Example XML file: bookstore.xml
<?xml version=”1.0″ encoding=”iso-8859-1″?>
<bookstore>
<book category=”COOKING” ID=”1″>
<title lang=”en”>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category=”CHILDREN” ID=”2″>
<title lang=”en”>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category=”WEB” ID=”3″>
<title lang=”en”>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Now Open a VS project and Add an XML file. Save the previous XML as XML file to the project XML file.
Just a sample UI to interact:
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”XmlExample1._Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Button ID=”btnParse” runat=”server” Text=”Parse XMLDoc With DOM Recurcive”
onclick=”btnParse_Click” />
<br />
<hr />
<asp:Label ID=”lblResult” runat=”server” Text=”"></asp:Label>
</div>
</form>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
namespace XmlExample1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnParse_Click(object sender, EventArgs e)
{
UsingXPTHSelectNode();
}
private void UsingXPTHSelectNode()
{
string s = “”;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(MapPath(“bookstore.xml”));
XmlNodeList nList;
nList = xmlDoc.SelectNodes(“//bookstore”);
foreach (XmlNode node in nList)
{
s = string.Format(” Type: {0} ;Name: {1}”, node.NodeType, node.Name);
lblResult.Text += s + “<br/>”;
if (node.HasChildNodes)
{
foreach (XmlNode child in node.ChildNodes)
{
s = string.Format(“Type:{0} Name: {1}; InnerText:{2}”, child.NodeType, child.Name, child.InnerText);
if (child.Attributes.Count > 0)
foreach (XmlAttribute att in child.Attributes)
s += string.Format(“ ATT: >> Type:{0}; Name: {1}; Inner Text:{2}”, att.NodeType, att.Name, att.Value);
lblResult.Text += s + “<br/>”;
}
}
}
}
}
}
Solution structure:

Output:

XML With XPATH
To get a more refine Example:
Simply Call the following function In place of previous function :
private void MoreRefinedUsingXPATHSelectNode()
{
string result = “”;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(MapPath(“bookstore.xml”));
XmlNode root = xmlDoc.DocumentElement;
result +=root.Name +”<br>” ;
foreach (XmlNode firstChild in root.ChildNodes)
{
result += “Start of Child <br>”;
result += firstChild.Name+ “<br> “;
foreach (XmlAttribute firstChildAtt in firstChild.Attributes)
result += firstChildAtt.Value + “<br> “;
foreach (XmlNode grandChind in firstChild.ChildNodes)
{
result += grandChind.Name + ” : ” + grandChind.InnerText +”<br>”;
}
result += “<br>End of Child<br>”;
}
lblResult.Text = result;
}
Output:

XML Using XPATH Refresh