key function with different parameters
File: Data.xml
<shirts>
<colors>
<color cid="c1">yellow</color>
<color cid="c2">black</color>
<color cid="c3">red</color>
<color cid="c4">blue</color>
<color cid="c5">purple</color>
<color cid="c6">white</color>
<color cid="c7">orange</color>
<color cid="c7">green</color>
</colors>
<shirt colorCode="c4">item 1</shirt>
<shirt colorCode="c1">item 2</shirt>
<shirt colorCode="c6">item 3</shirt>
</shirts>
File: Transform.xslt
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="text" />
<xsl:key name="colorNumKey" match="color" use="@cid" />
<xsl:key name="colorKey" match="color" use="." />
<xsl:variable name="testVar">c4</xsl:variable>
<xsl:variable name="keyName">colorKey</xsl:variable>
<xsl:template match="colors">
Looking up the color name with the color ID:
c3's color:
<xsl:value-of select="key('colorNumKey','c3')" />
c4's color:
<xsl:value-of select="key('colorNumKey',$testVar)" />
c8's color:
<xsl:value-of select="key('colorNumKey','c8')" />
c7's colors:
<xsl:for-each select="key('colorNumKey','c7')">
<xsl:value-of select="." />
<xsl:text> </xsl:text>
</xsl:for-each>
Looking up the color ID with the color name:
blue's cid:
<xsl:value-of select="key('colorKey','blue')/@cid" />
black's cid:
<xsl:value-of select="key($keyName,'black')/@cid" />
gray's cid:
<xsl:value-of select="key('colorKey','gray')/@cid" />
</xsl:template>
<xsl:template match="shirt" />
</xsl:stylesheet>
Output:
Looking up the color name with the color ID:
c3's color:
red
c4's color:
blue
c8's color:
c7's colors:
orange green
Looking up the color ID with the color name:
blue's cid:
c4
black's cid:
c2
gray's cid:
Related examples in the same category