RE: [xsl] which is faster?

Subject: RE: [xsl] which is faster?
From: "Andrew Welch" <ajwelch@xxxxxxxxxxxxxxx>
Date: Fri, 4 Feb 2005 14:28:02 -0000
> Thanks.
> I can only seem to get that to work if I define the key outside the
> template... is this normal?

Yes - xsl:key is a 'top-level element' which means it must be a child of
the xsl:stylesheet or xsl:transform elements.  With XSLT it's best not
to guess, as you will invariably guess wrong :)

> Also. Why do you sugest going:
>
>
> <xsl:variable name="autodate"
> select="document('/global/autodate.xml')"/>
> <xsl:key name="autodate_month" match="month" use="@position"/>
>
> <xsl:for-each select="$autodate">
> <xsl:value-of select="key('autodate_month',
> $month_position)/@name"/> </xsl:for-each>
>
>
> what is the purpose of that for-each loop? Could you not just go:
>
> <xsl:variable name="autodate"
> select="document('/global/autodate.xml')"/>
> <xsl:key name="autodate_month" match="month" use="@position"/>
>
> <xsl:value-of select="key('autodate_month', $month_position)/@name"/>

The purpose is to change the context node to the document that you want
to key into.  A key only works on the document that contains the context
node (in XSLT 1.0) so in order for the key to work on autodate.xml and
not the original source xml, you have to first change to it using
xsl:for-each (a good design tip for beginners here is to only ever use
xsl:for-each to change the context node).  In XSLT 2.0 the key()
function can take the document to key into as a 3rd argument, which
means there's no longer the need to wrap it in a for-each.

> well the answer is no! I just tried it and it doesn't work...
> but why not?
> You are not using anything from that xsl:for-each loop in the call to
> xsl:value-of are you?

You're guessing again! The reason why it doesn't work is because without
first changing the context node (by wrapping the call in a for-each) the
key is being applied to the current document and not autodate.xml

cheers
andrew

Current Thread