Simple test for odd and even numbers

Written by James McDonald

January 11, 2011

I was just looking at this sites XML sitemap in my browser and got to wondering how it is displayed in such a nicely human readable format.

Looking at the source of the sitemap.xml shows that it references an XSL style sheet. https://toggen.com.au/wp-content/plugins/google-sitemap-generator/sitemap.xsl

What grabbed my attention is how it nicely loops through the XML nodes and adds a CSS class of “high” to the tables rows and makes the background a different colour.

It does the test for oddness and even-ness using an XSLT function position() and piece of simple math. I won’t explain it because that’s what Wikipedia is for and I barely understand it myself but you use the mod operator to get whether the record is a odd or even number.

1 mod 2 = 1
2 mod 2 = 0
3 mod 2 = 1
4 mod 2 = 0
5 mod 2 = 1
6 mod 2 = 0

So the sitemap XSLT shown in the following code snippet creates a table with nice bold headings and then loops through the sitemap.xml and creates the table data with every second row highlighted using CSS

<table cellpadding="5">
  <tr style="border-bottom:1px black solid;">
    <th>URL</th> 
    <th>Priority</th> 
    <th>Change Frequency</th> 
    <th>LastChange (GMT)</th> 
  </tr>
  <xsl:variable name="lower" select="'abcdefghijklmnopqrstuvwxyz'" /> 
  <xsl:variable name="upper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" /> 
<xsl:for-each select="sitemap:urlset/sitemap:url">
<tr>
<!-- Test for oddness and evenness -->
<xsl:if test="position() mod 2 != 1">
    <!-- add a css class with a value of high -->
  <xsl:attribute name="class">high</xsl:attribute> 
  </xsl:if>
<td>
<xsl:variable name="itemURL">
<xsl:value-of select="sitemap:loc" /> 
  </xsl:variable>
<a href="{$itemURL}">
  <xsl:value-of select="sitemap:loc" /> 
</a>
  </td>
<td>
  <xsl:value-of select="concat(sitemap:priority*100,'%')" /> 
  </td>
<td>
  <xsl:value-of select="concat(translate(substring(sitemap:changefreq, 1, 1),concat($lower, $upper),concat($upper, $lower)),substring(sitemap:changefreq, 2))" /> 
  </td>
<td>
  <xsl:value-of select="concat(substring(sitemap:lastmod,0,11),concat(' ', substring(sitemap:lastmod,12,5)))" /> 
  </td>
  </tr>
  </xsl:for-each>
  </table>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…