Random Items in XSLT

前端 未结 5 1035
轮回少年
轮回少年 2020-12-17 18:18

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

相关标签:
5条回答
  • 2020-12-17 18:37

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

    0 讨论(0)
  • 2020-12-17 18:43

    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>
    
    0 讨论(0)
  • 2020-12-17 18:51

    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 讨论(0)
  • 2020-12-17 18:53

    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.

    0 讨论(0)
  • 2020-12-17 18:56

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

    0 讨论(0)
提交回复
热议问题