RE: [xsl] question on random numbers for browser XSLT

Subject: RE: [xsl] question on random numbers for browser XSLT
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Fri, 24 Jul 2009 22:43:28 +0100
> >   <xsl:template name="rand">
> >     <xsl:param name="scale" select="6" />
> >     <xsl:variable name="seed" />
> >     <xsl:choose>
> >       <xsl:when test="function-available('exsl:node-set')">
> >         <xsl:value-of select="document(concat('/cgi-bin/rand.pl?', 
> > $scale, '&amp;x=', generate-id(exsl:node-set($seed))))" />
> >       </xsl:when>
> >       <xsl:when test="function-available('msxsl:node-set')">
> >         <xsl:value-of select="document(concat('/cgi-bin/rand.pl?', 
> > $scale, '&amp;x=', generate-id(msxsl:node-set($seed))))" />
> >       </xsl:when>
> >     </xsl:choose>
> >   </xsl:template>
> > 
> > </xsl:stylesheet>
> > 
> > 
> > That'll give you six random values, assuming the Perl script 
> > recognizes the &x=Idxxxxx as cache-append garbage.
> 
> Interesting approach however when I test it with browsers 
> then Firefox (3.0), Opera (9.63) and Safari (3.2) all seem to 
> generate the same id each time that template is called:
> http://home.arcor.de/martin.honnen/xslt/test2009072402.xml
> (stylesheet: 
> http://home.arcor.de/martin.honnen/xslt/test2009072402Xsl.xml)
> 
> Only IE (tested with IE 8) generates different ids.
> 

In XSLT 1.0 (I was surprised to rediscover just now), the value of variable
$seed is not a result tree fragment, it is a zero-length string. So I'm a
little bit surprised that exslt:node-set() should work on it at all, and not
particularly surprised that it should generate the same node-set each time.

Now, suppose you used a real result-tree-fragment like

<xsl:variable name="seed"><a/></xsl:variable>

I think that technically a conformant processor ought to generate a new
temporary tree with distinct identity for the variable $seed each time that
the template is called, which means you should get a different generate-id()
each time. But relying on this is tempting providence: you're in the final
0.1% of edge cases for conformance, and some of the XSLT processors out
there depart from the spec well before you get that close to the edge. Apart
from anything else, extensions functions like exslt:node-set() take you
outside the scope of the spec anyway.

Regards,

Michael Kay
http://www.saxonica.com/
http://twitter.com/michaelhkay 

Current Thread