Working with Expressions, Variables and xsl:for-each in XSLT - Generating serial numbers when working with xsl:for-each
(Page 5 of 6 )
When we generate tables from the existing XML data, there may be a need to generate serial numbers in the first column of every row fetched by “xsl:for-each.”
The following is a simple solution to deal with this issue:
<?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 width="50%" cellspacing="0" cellpadding="0" style="font-
family:verdana;font-size:X-Small" border="1">
<tr bgcolor="#336699">
<th>
</th>
<th align="left">
<font color="White">ID</font>
</th>
<th align="right">
<font color="White">Name</font>
</th>
<th align="right">
<font color="White">Salary</font>
</th>
<th align="right">
<font color="White">Department</font>
</th>
</tr>
<xsl:for-each select="SQLData/Rows">
<tr>
<td align="left">
<xsl:number count="*" format="1. "/>
</td>
<td align="left">
<xsl:value-
of select="Empno" />
</td>
<td align="right">
<xsl:value-
of select="Ename" />
</td>
<td align="right">
<xsl:value-of select="Sal" />
</td>
<td align="right">
<xsl:value-
of select="Deptno" />
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
When the above code gets executed, you are likely to get the following transformation:
<table width="50%" cellspacing="0" cellpadding="0" style="font-
family:verdana;font-size:X-Small" border="1">
<tr bgcolor="#336699">
<th />
<th align="left">
<font color="White">ID</font>
</th>
<th align="right">
<font color="White">Name</font>
</th>
<th align="right">
<font color="White">Salary</font>
</th>
<th align="right">
<font color="White">Department</font>
</th>
</tr>
<tr>
<td align="left">1. </td>
<td align="left">1001</td>
<td align="right">Jag</td>
<td align="right">4400</td>
<td align="right">10</td>
</tr>
<tr>
<td align="left">2. </td>
<td align="left">1002</td>
<td align="right">Chat</td>
<td align="right">2800</td>
<td align="right">20</td>
</tr>
.
.
.
</table>
Next: Working with xsl:choose within xsl:for-each in XSLT >>
More ASP.NET Articles
More By Jagadish Chaterjee