Displaying a random list item with XSL

This week I re-discovered a technique for displaying a random item from a list using XSL. This can apply to both Content Query Web Parts (CQWP) and XSLT List View Web Parts (XLV) and is actually a very trivial piece of XSL.

The technique goes something like:

  1. Get a count of how many items to choose a random item from, say RowCount
  2. Return a random number between 1 and RowCount
  3. Use that random number to display a list item

The important bit is discovering/ remembering that there is a function available to use in SharePoint in the ddwrt namespace that generates a random number between two given numbers. It is this ddwrt:Random(1, RowCount) function that allows us to achieve our objective.

The XSL could look something like this:

<xsl:stylesheet 
  version="1.0" 
  exclude-result-prefixes="x d xsl ddwrt"
  xmlns:x="http://www.w3.org/2001/XMLSchema" 
  xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime">
  <xsl:template match="/">
	<xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row" />
	<xsl:variable name="RowCount" select="count($Rows)" />
	<xsl:variable name="RandomNumber" select="ddwrt:Random(1, $RowCount)" />
	
	<xsl:for-each select="$Rows[position() = $RandomNumber]">
		<xsl:value-of select="@Title" />
	</xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

Note, even though we’re only displaying a single item we are still querying and returning potentially many items. For this reason I’d only recommend using this technique on relatively small lists.

share and enjoy
  • Print
  • Twitter
  • Digg
  • del.icio.us
  • StumbleUpon
  • Yahoo! Buzz
  • Google Bookmarks
  • Facebook

4 comments to Displaying a random list item with XSL

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>