cbx
cbx

Reputation: 21

Randomize sorting in xslt 1.0?

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

Upvotes: 0

Views: 1395

Answers (2)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56182

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.

Upvotes: 0

Tomalak
Tomalak

Reputation: 338316

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>

Upvotes: 1

Related Questions