Welcome to AspAdvice Sign in | Join | Help

Alternate Table Row Colors with XSL

This XSL file is from an article I wrote entitled: Displaying XML Files with ASP.NET 2.0. So, how do you alternate row colors? Compare the these two XSL files.

Original XSL file from the article:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes"/>
<xsl:template match="/">
<table>
<tr bgcolor="#99aacc">
<th>Last Name</th>
<th>First Name</th>
<th>Phone</th>
</tr>
<xsl:for-each select="NewDataSet/authors">
<xsl:sort select="au_lname"/>
<tr bgcolor="#aaccff">
<td><xsl:value-of select="au_lname"/></td>
<td><xsl:value-of select="au_fname"/></td>
<td><xsl:value-of select="phone"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>

Make this change to alternate row colors:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes"/>
<xsl:template match="/">
<table>
<tr bgcolor="#99aacc">
<th>Last Name</th>
<th>First Name</th>
<th>Phone</th>
</tr>
<xsl:for-each select="NewDataSet/authors">
<xsl:sort select="au_lname"/>

<xsl:if test="position()  mod 2 = 1">
<tr bgcolor="#aaccff">
<td><xsl:value-of select="au_lname"/></td>
<td><xsl:value-of select="au_fname"/></td>
<td><xsl:value-of select="phone"/></td>
</tr>
</xsl:if>

<xsl:if test="position()  mod 2 = 0">
<tr bgcolor="#ffccaa">
<td><xsl:value-of select="au_lname"/></td>
<td><xsl:value-of select="au_fname"/></td>
<td><xsl:value-of select="phone"/></td>
</tr>
</xsl:if>

</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>


 

Published Wednesday, May 11, 2005 7:17 AM by andrewmooney
Filed under:

Comments

# re: Alternate Table Row Colors with XSL

Thursday, June 23, 2005 9:38 AM by andrewmooney
Change to apply to this code
<code>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes"/>
<xsl:template match="/">
<table>
<tr bgcolor="#99aacc">
<th>Last Name</th>
<th>First Name</th>
<th>Phone</th>
</tr>
<xsl:for-each select="NewDataSet/authors">
<xsl:sort select="au_lname"/>
<tr>
<xsl:attribute name="class"><xsl:choose><xsl:when test="position() mod 2 = 1">tablerowon</xsl:when><xsl:when test="position() mod 2 = 0">tablerowoff</xsl:when></xsl:choose></xsl:attribute>
<td class="class">
<xsl:value-of select="au_lname"/>
</td>
<td class="class">
<xsl:value-of select="au_fname"/>
</td>
<td class="class">
<xsl:value-of select="phone"/>
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>

</code>
Anonymous comments are disabled