tags:

views:

401

answers:

4

I'm customizing a Google Search appliance, which uses XSLT to present results to the user. Our design calls for one of several images to be included randomly on the results page. Is there a way to use randomness in XSLT? (Pseudo-randomness is just fine for this application.)

Calling random templates would be fine, as would just being able to generate a random number and branch based on that.

+2  A: 

Depending on your platform XSL allows inject of user code like C#. I don't recommend this. Better, I would have your XSL accept a parameter and whatever is generating your XML payload or XSLT and can also generate the random number, setting the parameter. I've done this exactly using this approach except the data came from Bing, not G.

No Refunds No Returns
How did you convince Bing to send you a random number? Or did you just take a query string or something and process it to get a number out of it? As far as I can tell, I don't have much control over the XML payload the Search Appliance generates.
Sean McMains
Randomness is generated by the bing API caller and the random number passed as a parameter. Bing gives you XML. You have an XSLT that accepts parameters. Merely bring buyer and seller together.
No Refunds No Returns
+1  A: 

If you are not averse to including libraries, there are many available such as random:random-sequence from EXSLT

Mike
Can't see using a library that implements random() when you have direct access to it via the run time environment.
dacracot
+1  A: 

If you use a Java based XSLT engine, this will allow you to make calls to any static method within the Java libraries, such as java.lang.Math.random(). Here is the syntax...

<?xml version='1.0'?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:math="java.lang.Math"
    version='1.1'>

    <xsl:template match="/">
        <xsl:variable name="myRandom" select="math:random()"/>
        <xsl:value-of select="$myRandom"/>
    </xsl:template>

</xsl:stylesheet>
dacracot
PS - It has to be XSL version 1.1 or higher.
dacracot
Cool trick! Unfortunately, the Search Appliance only seems interested in XSLT v1.0. Rats!
Sean McMains
A: 

You can generate in pure XSLT sequences of random numbers and also random permutations of the numbers in [1 .. N].

Just use the FXSL library (written in pure XSLT) for this.

This article explains the templates to use and has complete examples:

"Casting the Dice with FXSL: Random Number Generation Functions in XSLT".

Dimitre Novatchev