Previous | Next | Indexes
Zvon > Tutorials > XSLT 2.0 Tutorial > Keys (10/12) >

Using keys in variables or parameters

The value of the third argument of key() function can be a variable or parameter. In such case keys are looked for inside the parameter or variable.

XSLT

      <xsl:stylesheet
                  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                  version="2.0">
            <xsl:output  method="xml"
                        indent="yes"
                        omit-xml-declaration="yes"/>
            <xsl:key  name="kkk"
                        match="ccc"
                        use="@c"/>

            <xsl:template  match="/aaa">
                  <xsl:apply-templates  select="bbb[1]">
                        <xsl:with-param  name="ppp"
                                    select="bbb[2]"/>
                  </xsl:apply-templates>
            </xsl:template>

            <xsl:template  match="bbb">
                  <xsl:param  name="ppp"/>
                  <xsl:variable  name="vvv">
                        <zzz>
                              <ccc  c="X">111</ccc>
                              <ccc  c="Y">222</ccc>
                              <ddd>
                                    <ccc  c="X">333</ccc>
                              </ddd>
                        </zzz>
                  </xsl:variable>
                  <xxx  id="{@id}">
                        <xsl:apply-templates  select="key('kkk','X',$ppp)"/>
                  </xxx>
                  <yyy>
                        <xsl:apply-templates  select="key('kkk','X',$vvv)"/>
                  </yyy>
            </xsl:template>

            <xsl:template  match="*">
                  <xsl:copy-of  select="."/>
            </xsl:template>

      </xsl:stylesheet>
XML

      <aaa>
            <bbb  id="b1">
                  <ccc  c="X">1</ccc>
                  <ccc  c="Y">2</ccc>
                  <ddd>
                        <ccc  c="X">3</ccc>
                  </ddd>
            </bbb>
            <bbb  id="b2">
                  <eee>
                        <fff>
                              <ccc  c="X">4</ccc>
                        </fff>
                  </eee>
            </bbb>
      </aaa>
Output

      <xxx  id="b1">
            <ccc  c="X">4</ccc>
      </xxx>
      <yyy>
            <ccc  c="X">111</ccc>
            <ccc  c="X">333</ccc>
      </yyy>


Previous chapter: Namespaces
Next chapter: Recursions
Previous page: Optional third argument of key function
Next page: A useful example of context change with the third argument of key