随机化节点顺序xslt [英] randomize node order xslt
问题描述
我有一个XML文件,其中包含如下所示的节点:
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>
我想使用xslt以随机顺序获取列表:
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>
我无法使用外部资源,例如 "xmlns:java =" java.lang.Math 和 "xmlns:math =" http://exslt.org/math"
I cannot use external resources like "xmlns:java="java.lang.Math" and "xmlns:math="http://exslt.org/math"
由于限制.
也许此链接可能会有所帮助:
maybe this links might help:
http://fxsl.sourceforge.净/文章/随机/铸造%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.
注意:由于只对项目进行了重新排序而不进行处理,因此无需对它们进行排序,并且这里完全不需要EXSLT node-set()函数. >
<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>
应用于具有默认初始种子(123)的输入,输出为:
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>
当种子为1234时执行,输出为:
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>
这篇关于随机化节点顺序xslt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!