views:

132

answers:

1

Is there a way to walk-through a key and output all the values it contains?

   <xsl:key name="kElement" match="Element/Element[@idref]" use="@idref" />

I though of it this way:

<xsl:for-each select="key('kElement', '.')">
  <li><xsl:value-of select="." /></li>
</xsl:for-each>

However, this does not work. I simply want to list all the values in a key for testing purposes.

The question is simply: how can this be done?

+2  A: 

You can't. That's not what keys are for.

You can loop through every element in a key using a single call to key() if and only if the key of each element is the same.

If you need to loop over everything the key is defined over, you can use the expression in the match="..." attribute of your <key> element.

So if you had a file like this:

<root>
  <element name="Bill"/>
  <element name="Francis"/>
  <element name="Louis"/>
  <element name="Zoey"/>
</root>

And a key defined like this:

<xsl:key name="survivors" match="element" use="@name"/>

You can loop through what the key uses by using the contents of its match attribute:

<xsl:for-each select="element">
  <!-- stuff -->
</xsl:for-each>

Alternatively, if each element had something in common:

<root>
  <element name="Bill" class="survivor"/>
  <element name="Francis" class="survivor"/>
  <element name="Louis" class="survivor"/>
  <element name="Zoey" class="survivor"/>
</root>

Then you could define your key like this:

<xsl:key name="survivors" match="element" use="@class"/>

And iterate over all elements like this:

<xsl:for-each select="key('survivors', 'survivor')">
  <!-- stuff -->
</xsl:for-each>

Because each element shares the value "survivor" for the class attribute.

In your case, your key is

<xsl:key name="kElement" match="Element/Element[@idref]" use="@idref" />

So you can loop through everything it has like this:

<xsl:for-each select="Element/Element[@idref]">
  <!-- stuff -->
</xsl:for-each>
Welbog
(+1) Makes sense. That answers my question.
Kris Van den Bergh
enjoyed the L4D reference, and this answer helped me too!
paulwhit