RE: [xsl] Keys (easy one) match on name()

Subject: RE: [xsl] Keys (easy one) match on name()
From: "Andrew Welch" <ajwelch@xxxxxxxxxxxxxxx>
Date: Wed, 1 Jun 2005 15:32:29 +0100
> Maybe that is where I have gone wrong, I assumed that the key
> definition is context aware.  So to write the select
> expression as I have as "field" would suffice in the case
> that my context is record; the immediate context from record
> is field. I have written keys, and use them quite a bit, but
> this one's twist is the fact that I am driving off on the
> name attribute.
>
> > key_fld of 'NeedCode'. Your expression that uses the predicate
> > directly only selects the field elements that are children of the
> > context node. Without
>
> So, If the current context is "record", where "record" has a bunch of
> "field"(s) for child elements, shouldn't this key lookup
> work? <xsl:key name="key_fld" match="field" use="@name"/>

The point is the document in which <field> exists.  For example:

Source xml:

<root>
  <field/>
</root>

And a variable in your stylesheet:

<xsl:variable name="var">
  <var>
    <field/>
  </var>
</xsl:variable>

Here there are two field elements, one in the source tree and one in a
different tree.  The key will only apply to one or the other, depending
on which tree the context node is in at the time of the call to the
key() function.

So, to key into the source XML just use the key() function.

To key into the variable, first change the context node to the variable,
using a for-each:

<xsl:for-each select="$var">
  <xsl:value-of select="key(...
</xsl:for-each>

If you need to key into the source xml from within the variable, you
will need to change the context node back to source xml (by using
another variable to point to /).

In 2.0 you don't need the for-each as the key() function contains a
third argument - the tree that the key should apply to.  So for the
example above you could write:

  <xsl:value-of select="key('aaa', bbb, $var)"/>

This is the key to your problem - at the point you are calling the key()
function the context node is in a document that is different to the one
you expect (most like a variable), giving no results.

cheers
andrew

Current Thread