开发者

Random Items in XSLT

I'm customizing a Google Search appliance, which uses XSLT to present results to the user. Our design calls for one of开发者_如何学Go 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.


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".


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.


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>


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


If you are doing this for anything Microsoft, I found that using XSLT's function ddwrt:Random works.

I use the following to create the random number

<xsl:variable name="RowCount" select="count($Rows)" />
<xsl:variable name="RandomNumber" select="ddwrt:Random(1, $RowCount)" />

and the following to present

<xsl:for-each select="$Rows[position() = $RandomNumber]">
<xsl:value-of select="@Title" /></xsl:for-each>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜