Learning XPath with XSLT using ASP.NET 2.0 - Retrieving all values of all elements at all levels of hierarchies (or paths)
(Page 6 of 6 )
In previous sections, we simply searched for a particular element throughout the document. Now, I would like to parse through every element (regardless of its path) within the document and display the values.
The following is the first approach for accomplishing the same (using a separate template):
<?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 ="//*"/>
</b>
</xsl:template>
<xsl:template match="*">
<xsl:value-of select ="text()"/>
<br/>
</xsl:template>
</xsl:stylesheet>
Within the above code, you can observe that I am using “//*”, which stands for “any element at any level”! The following is the second approach for accomplishing the same (using “xsl:for-each” construct).
<?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="//*">
<xsl:value-of select="text()"/>
<br/>
</xsl:for-each>
</b>
</xsl:template>
</xsl:stylesheet>
In any of the above cases, when the XSLT gets executed, the transformation looks something like the following (I have added comments for understanding):
<b>
<br /> (for EmployeeDetails)
<br /> (for Department)
<br /> (for Employee)
1001<br /> (for Empno)
Jagadish<br /> (For Ename)
3400<br /> (For Sal)
<br /> (for Employee)
1002<br /> (for Empno)
Chatarji<br /> (for Ename)
2500<br /> (for Sal)
<br /> (for Employee)
.
.
.
</b>
In the upcoming articles, we shall look further into XPath expressions. I hope you enjoyed the article and any comments, suggestions, feedback, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |