Randomize sorting in xslt 1.0?

≯℡__Kan透↙ 提交于 2020-02-06 09:02:54

问题


I would like to know, is there is any way to do random sorting in XSLT 1.0?

Here is my XML

<root><DO status="a">text comes here</DO><DO status="b">text comes here</DO><DO status="c">text comes here</DO><DO status="d">text comes here</DO><DO status="e">text comes here</DO></root>

Desired Output:

<root><DO status="c">text</DO><DO status="a">text comes here</DO><DO status="b">text comes here</DO><DO status="e">text comes here</DO><DO status="d">text comes here</DO></root>

Hope my question is clear?

Thanks in advance


回答1:


I would like to know, is there is any way to do random sorting in XSLT 1.0?

With vanilla XSLT 1.0 - No.

You could use an extension to access the randomizer of an external language and put that function into xsl:sort. For example, using the msxsl extension to access Windows Scripting languages:

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:msxsl="urn:schemas-microsoft-com:xslt"
  xmlns:my="http://tempuri.org/myscripts" 
  exclude-result-prefixes="msxsl my"
>

  <msxsl:script language="JScript" implements-prefix="my">
    function random() {
      return Math.random();
    }
  </msxsl:script>

  <xsl:template match="root">
    <xsl:for-each select="DO">
      <xsl:sort select="my:random()" data-type="number" />
      <xsl:copy-of select="." />
    </xsl:for-each>
  </xsl:template> 

</xsl:stylesheet>



回答2:


You can use XSLT generate-id() function which returns a string that uniquely identifies a node in the document. In accordance with specification:

An implementation is free to generate an identifier in any convenient way provided that it always generates the same identifier for the same node and that different identifiers are always generated from different nodes. An implementation is under no obligation to generate the same identifiers each time a document is transformed. There is no guarantee that a generated unique identifier will be distinct from any unique IDs specified in the source document.

So it depends on your XSLT processor.



来源:https://stackoverflow.com/questions/6607124/randomize-sorting-in-xslt-1-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!