Doing interesting things with XSL

I’ve been messing around with using XSL to display RSS on MSDN, as a simpler alternative to a custom ASP.NET control, and while it works perfectly in the core case (display all the items in a feed in a format), there are two additional requirements that were very easy to handle in a .NET class, but trickier (for me) in XSL.

  • Display the top n items
  • Out of the full list, display n randomly picked items

For the first, it was pretty easy… <xsl:if test=”position < 6″> could be used to only output the top 5 items, for example… For the second though, I was stumped for a bit… then I came up with an idea. I would write a script function that would pick n items out of the total count, put those choices into an array, then use another function that tests the current position against that list of choices… sound good? Well, I’m still working on implementing this one… I have it working, but I’m not 100% sure of my solution.

If you are interested, you can see the code running here, and pull down the xsl from here, and the backing rss file from here. Code for the pageCode for the control it references

Author: Duncan Mackenzie

I'm the Developer Lead for the Channel 9 team, formerly worked on MSDN as a developer, content strategist and author.

2 thoughts on “Doing interesting things with XSL”

  1. &gt;&gt;Out of the full list, display n randomly picked items

    How about using generate-id(), which will be pretty random on each run, and then sort by the generate-id()?

  2. Sorry, previous response was dumb. It will give you the same values each time on the same document (although it would be random when the contents of the site changed).

    However, something like this will work — just supply a $seed argument along with your $numberToShow:

    &lt;xsl:apply-templates select=”channel/item” &gt;
    &lt;xsl:sort select=”substring(substring-after( position() div $seed ,’.’),3,5)”

    … the above assumes a positive/large seed number but you can obviously adapt if you’re using a fractional seed number.


Leave a Reply