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.

You May Also Like…


Zebra Printer Language The above website has a page where you can enter ZPL and it...

PHP Iterators

Just came across a Youtube talk "Iterators in PHP" by Jake Smith published in 2014 that steps through the many...