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.

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>Change Frequency</th> 
    <th>LastChange (GMT)</th> 
  <xsl:variable name="lower" select="'abcdefghijklmnopqrstuvwxyz'" /> 
  <xsl:variable name="upper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" /> 
<xsl:for-each select="sitemap:urlset/sitemap:url">
<!-- 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:variable name="itemURL">
<xsl:value-of select="sitemap:loc" /> 
<a href="{$itemURL}">
  <xsl:value-of select="sitemap:loc" /> 
  <xsl:value-of select="concat(sitemap:priority*100,'%')" /> 
  <xsl:value-of select="concat(translate(substring(sitemap:changefreq, 1, 1),concat($lower, $upper),concat($upper, $lower)),substring(sitemap:changefreq, 2))" /> 
  <xsl:value-of select="concat(substring(sitemap:lastmod,0,11),concat(' ', substring(sitemap:lastmod,12,5)))" /> 


Submit a Comment

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

You May Also Like…

Toggen builds a new website

So I have built and hosted a new website for Roger Clark Pest Management they are a family owned and operated Pest...


Just downloaded WizTree (not a sponsor) from It seems to do what it says on the tin which is...

Scam call from “Telstra”

Just had a call from a man with a sub-continental accent from caller ID 0734946596 Told me there was problem with my...