Learning XPath with XSLT using ASP.NET 2.0 - Retrieving all values of a particular element at any level of hierarchy (or path)
(Page 5 of 6 )
We already retrieved all employee names using the XSLT code given in the previous section. The code given in that section always deals with the “Ename” existing only at “EmployeeDetails/Department/Employee.”
If I have the “Ename” at different levels of the hierarchy (but not in my XML document yet), the XSLT given in the previous section will not work. The following is the modified code (using separate template) to retrieve the value of “Ename” at any level of the hierarchy:
<?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 ="//Ename"/>
</b>
</xsl:template>
<xsl:template match="Ename">
<xsl:value-of select ="text()"/>
<br/>
</xsl:template>
</xsl:stylesheet>
You can observe that I replaced “EmployeeDetails/Department/Employee” with a simple “//Ename.” The “//” simply gives the instruction “at any level of hierarchy.” Similarly, the following is the modified code (using “xsl:for-each” construct) to retrieve the value of “Ename” at any level of hierarchy:
<?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="//Ename">
<xsl:value-of select="text()"/>
<br/>
</xsl:for-each>
</b>
</xsl:template>
</xsl:stylesheet>
The output of any of the above transformations would be the same (in this case), as given in the previous section. You may find it different if you really have “Ename” at different levels of hierarchies (or paths).
Next: Retrieving all values of all elements at all levels of hierarchies (or paths) >>
More ASP.NET Articles
More By Jagadish Chaterjee