I have an XML file that contains nodes like this:
<values>
<item>item 1</item>
<item>item 2</item>
<item>item 3</item>
<item>item 4</item>
<item>item 5</item>
</values>
I would like to get the list in a randomize order using xslt:
<values>
<item>item 3</item>
<item>item 5</item>
<item>item 1</item>
<item>item 4</item>
<item>item 2</item>
</values>
I cannot use external resources like
"xmlns:java="java.lang.Math"
and
"xmlns:math="http://exslt.org/math"
because of limitation.
maybe this links might help:
http://fxsl.sourceforge.net/articles/Random/Casting%20the%20Dice%20with%20FXSL-htm.htm
The following stylesheet will write the items to the output tree in random order. The stylesheet expects an external "initial-seed" number to be supplied at runtime as a parameter.
Note: since the items are only re-ordered without processing, it is not necessary to sort them, and the EXSLT node-set() function will not be required here after all.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:param name="initial-seed" select="123"/>
<xsl:template match="/">
<values>
<xsl:call-template name="pick-random-item">
<xsl:with-param name="items" select="values/item"/>
</xsl:call-template>
</values>
</xsl:template>
<xsl:template name="pick-random-item">
<xsl:param name="items" />
<xsl:param name="seed" select="$initial-seed"/>
<xsl:if test="$items">
<!-- generate a random number using the "linear congruential generator" algorithm -->
<xsl:variable name="a" select="1664525"/>
<xsl:variable name="c" select="1013904223"/>
<xsl:variable name="m" select="4294967296"/>
<xsl:variable name="random" select="($a * $seed + $c) mod $m"/>
<!-- scale random to integer 1..n -->
<xsl:variable name="i" select="floor($random div $m * count($items)) + 1"/>
<!-- write out the corresponding item -->
<xsl:copy-of select="$items[$i]"/>
<!-- recursive call with the remaining items -->
<xsl:call-template name="pick-random-item">
<xsl:with-param name="items" select="$items[position()!=$i]"/>
<xsl:with-param name="seed" select="$random"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Applied to your input with the default initial-seed (123), the output is:
<?xml version="1.0" encoding="utf-8"?>
<values>
<item>item 2</item>
<item>item 3</item>
<item>item 1</item>
<item>item 4</item>
<item>item 5</item>
</values>
When performed with a seed of 1234, the output is:
<?xml version="1.0" encoding="utf-8"?>
<values>
<item>item 4</item>
<item>item 1</item>
<item>item 5</item>
<item>item 2</item>
<item>item 3</item>
</values>