Working with Expressions, Variables and xsl:for-each in XSLT - Working with simple variables in XSLT
(Page 2 of 6 )
In the previous section, we were able to display all the employee details along with their salaries and annual salaries. We calculated annual salaries using expressions within “xsl:value-of.”
Now, we shall achieve the same using variables in XSLT. The following is the entire code rewritten for this purpose:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<table border="1">
<xsl:apply-templates select="SQLData/Rows" />
</table>
</xsl:template>
<xsl:template match="SQLData/Rows">
<tr>
<td>
<xsl:value-of select="Empno"/>
</td>
<td>
<xsl:value-of select="Ename"/>
</td>
<xsl:apply-templates select="Sal" />
<td>
<xsl:value-of select="Deptno"/>
</td>
</tr>
</xsl:template>
<xsl:template match="Sal">
<td>
<xsl:value-of select="text()"/>
</td>
<xsl:variable name="AnnSal" select="text()"/>
<td>
<xsl:value-of select="$AnnSal * 12"/>
</td>
</xsl:template>
</xsl:stylesheet>
The output of the above code would be the same as that of the previous section.
Coming to the explanation of the above code, every variable in XSLT must be declared using the “xsl:variable.” The value can be directly assigned using the “select” attribute or in the form of content.
To use variables at other parts of the same XSLT, just specify the name of the variable and precede it with the symbol “$”.
Next: Working with xsl:for-each in XSLT >>
More ASP.NET Articles
More By Jagadish Chaterjee