Learning XPath with XSLT using ASP.NET 2.0 - Retrieving all values of a particular element at a particular level of hierarchy (or path)
(Page 4 of 6 )
Let us go through our XSL sample listed in the previous section:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<b>
<xsl:value-of select="EmployeeDetails/Department/Employee/Ename"/>
</b>
</xsl:template>
</xsl:stylesheet>
According to the above, I defined a template to display some information when the control starts at “root” (or “/”). Within the template, I am displaying the value of “EmployeeDetails/Department/Employee/Ename.” In this case, it starts right from the root, proceeds along the path and finds the first employee name. The same gets displayed to the user.
Now, let us consider that I would like to display all the employee names. We have two good solutions for achieving the same. The first solution will use a separate template for that “Ename” element. You can observe the following code:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<b>
<xsl:apply-templates select ="EmployeeDetails/Department/Employee/Ename"/>
</b>
</xsl:template>
<xsl:template match="EmployeeDetails/Department/Employee/Ename">
<xsl:value-of select ="text()"/><br/>
</xsl:template>
</xsl:stylesheet>
The other method involves using “xsl:for-each.” If you are new to this construct, I suggest you go through the third and fourth articles of my previous series. The following is the code to achieve the same:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<b>
<xsl:for-each select="EmployeeDetails/Department/Employee/Ename">
<xsl:value-of select="text()"/>
<br/>
</xsl:for-each>
</b>
</xsl:template>
</xsl:stylesheet>
In either of the above cases, when the XSLT gets executed, the transformation looks something like the following:
<b>
Jagadish<br />
Chatarji<br />
Winner<br />
Dhanam<br />
Chinna<br />
Pedda<br />
Ram<br />
Robert<br />
Rahim<br />
</b>
Next: Retrieving all values of a particular element at any level of hierarchy (or path) >>
More ASP.NET Articles
More By Jagadish Chaterjee