Dealing with Attributes and Elements in XPath with XSLT using ASP.NET 2.0 - Searching for an element at a particular location
(Page 6 of 6 )
In this final section, I would like to deal with the elements available at a particular location. That means I would like provide a transformation for an “nth” element.
To work with the position (or index) of elements, we need to work with an XPath function called “position().” The following is the first approach we can use to accomplish the task (using separate templates).
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:apply-templates select ="EmployeeDetails/Department[position() = 2]"/>
</xsl:template>
<xsl:template match="EmployeeDetails/Department">
<b>Department: <xsl:value-of select ="@Dname"/></b><hr />
<xsl:apply-templates select ="Employee"/>
<br/>
</xsl:template>
<xsl:template match ="Employee" >
<xsl:value-of select ="Empno"/>,
<xsl:value-of select ="Ename"/>,
<xsl:value-of select ="Sal"/><br />
</xsl:template>
</xsl:stylesheet>
From the above, you can understand that I specified that the position must be 2 (or the second element). The following is the second approach we can use to deal with the same task (using an “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="/">
<xsl:for-each select="EmployeeDetails/Department[position() = 2]">
<b>
Department: <xsl:value-of select ="@Dname"/>
</b>
<hr />
<xsl:for-each select="Employee">
<xsl:value-of select ="Empno"/>,
<xsl:value-of select ="Ename"/>,
<xsl:value-of select ="Sal"/><br />
</xsl:for-each>
<br />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
In any of the above cases, when the XSLT gets executed, the transformation would look something like the following:
<b> Department: Sales</b>
<hr />
2001, Dhanam, 4500<br />
2002, Chinna, 3400<br />
2003, Pedda, 3200<br />
<br />
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. |