Re: [xsl] Marking every second row

Subject: Re: [xsl] Marking every second row
From: Peter Finch <peter@xxxxxxxxxxx>
Date: Tue, 07 Jan 2003 00:51:12 +1100
Hi Sorin,

> I got an very simple XSL-File wich produces following output from a very
> simple XML-File
>
> <table>
> <tr><td>aaa</td></tr>
> <tr><td>bbb</td></tr>      <-- X
> <tr><td>ccc</td></tr>
> <tr><td>ddd</td></tr>      <-- X
> <tr><td>eee</td></tr>
> <tr><td>fff</td> </tr>      <-- X
> </table>
>
>
> Now I want the background of the lines which are marked with an X in
> another color.

Given the following XML document there are a couple of ways to
do this, take you pick. Method [B] is a little tricky as you
have to select ONLY the ROW's in the root XPath select statement
"data/row" so that the position() function will return
(1,2,3,4,5,6). If you just use "data" then the XPath will include
the CData in the node-set and the <row> elements will appear
in positions (2,4,6,8,10,12). Personally, I like method [A], but
it does mean a duplication in markup.

<?xml version="1.0" ?>
<?xml-stylesheet href="oddeven.xsl" type="text/xsl"?>
<data>
<row>aaa</row>
<row>bbb</row>
<row>ccc</row>
<row>ddd</row>
<row>eee</row>
<row>fff</row>
</data>

Method [A] - Use template selection criteria

<xsl:template match="/">
 <table border="1">
  <xsl:apply-templates select="/data"/>
 </table>
</xsl:template>

<xsl:template match="row[(position() mod 2) = 0]">
 <tr>
  <td bgcolor="#E0E0E0">
   <xsl:apply-templates/>
  </td>
 </tr>
</xsl:template>

<xsl:template match="row[(position() mod 2) = 1]">
 <tr>
  <td bgcolor="#0000E0">
   <xsl:apply-templates/>
  </td>
 </tr>
</xsl:template>

Method [B] - Use a condition

<xsl:template match="/">
 <table border="1">
  <xsl:apply-templates select="/data/row"/>
 </table>
</xsl:template>

<xsl:template match="row">
 <tr>
  <td>
   <xsl:variable name="row" select="position() mod 2"/>
   <xsl:choose>
    <xsl:when test="$row = 0)">
     <xsl:attribute name="bgcolor">#F00000</xsl:attribute>
    </xsl:when>
    <xsl:when test="$row = 1)">
     <xsl:attribute name="bgcolor">#0000F0</xsl:attribute>
    </xsl:when>
   </xsl:choose>
   <xsl:apply-templates/>
  </td>
 </tr>
</xsl:template>

Happy coding...
Peter

--
   ___
  (OvO)
  /:::\
  \|:|/
/--m-m--------------------------------+
| Peter Finch (p.finch@xxxxxxxxxxx)   |
| Home Planet Software                |
| http://www.homepla.net/             |
/-------------------------------------/




XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list



Current Thread