在XSLT中随机选择一个节点

Kim*_*sen 7 xml random xslt umbraco

我对XSLT中的某种随机函数有疑问.

我有一个非常简化的XML文件,类似于:

<node id="1198">
  <node id="1201">
    <data alias="name">Flemming</data>
    <data alias="picture">1200</data>
  </node>
  <node id="1207">
    <data alias="name">John</data>
    <data alias="picture">1205</data>
  </node>
  <node id="1208">
    <data alias="name">Michael</data>
    <data alias="picture">1206</data>
  </node>
</node>
Run Code Online (Sandbox Code Playgroud)

我想有一些XSLT,ramdomly接受一个节点id并将其放入一个名为"choosenNode"的变量中.像这样,如果ID为1207的节点是选中的节点:

<xsl:variable name="choosenNode" value="1207" />
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?XSLT中是否有随机函数?顺便说一句,我希望在包含XSLT的每个页面上刷新变量.

我在Umbraco CMS工作,如果这对你们有帮助的话.

谢谢,-Kim

Tim*_*ers 7

在Umbraco你可以这样做:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:Stylesheet [ <!ENTITY nbsp "&#x00A0;"> ]>
<xsl:stylesheet 
version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:msxml="urn:schemas-microsoft-com:xslt"
xmlns:umbraco.library="urn:umbraco.library"
xmlns:Exslt.ExsltMath="urn:Exslt.ExsltMath"
exclude-result-prefixes="msxml umbraco.library Exslt.ExsltMath">

<xsl:output method="xml" omit-xml-declaration="yes"/>

<xsl:param name="currentPage"/>

<!-- This should probably be a macro parameter so you can use this elsewhere-->
<xsl:variable name="parentNode" select="1048"/>

<xsl:template match="/">

        <xsl:variable name="numberOfNodes" select="count(umbraco.library:GetXmlNodeById($parentNode)/node)"/>

        <xsl:variable name="randomPosition" select="floor(Exslt.ExsltMath:random() * $numberOfNodes) + 1"/>

        <xsl:variable name="randomNode" select="umbraco.library:GetXmlNodeById($parentNode)/node [position() = $randomPosition]"/>

        <!--
          You now have the node in the $randomNode variable
          If you just want the id then you can do an XPath query on the variable
          or you can modify the XPath above to get the property you are after rather than
          the whole node
        -->

    <xsl:value-of select="$randomNode/@nodeName" />

</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

蒂姆