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

Optional third argument of key() function

An optional third argument of key() function can be used to restrict the part of source XML tree where the key looks for matches.

In this example the first usage of key() finds all ccc elements in the document with the value of "c" attribute equal 'X'. The second key() uses its third argument to restrict its scope to the node bbb with id='b2' and all its descendants.

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">
                  <xxx>
                        <xsl:apply-templates  select="key('kkk','X')"/>
                  </xxx>
                  <yyy>
                        <xsl:apply-templates  select="key('kkk','X',bbb[@id='b2'])"/>
                  </yyy>
            </xsl:template>

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

      </xsl:stylesheet>
XML

      <aaa>
            <bbb  id="b1">
                  <ccc  c="X">1</ccc>
                  <ccc  c="Y">2</ccc>
            </bbb>
            <bbb  id="b2">
                  <ccc  c="X">3</ccc>
                  <ccc  c="Y">4</ccc>
            </bbb>
            <bbb  id="b3">
                  <ccc  c="X">5</ccc>
                  <ccc  c="Y">6</ccc>
            </bbb>
      </aaa>
Output

      <xxx>
            <ccc  c="X">1</ccc>
            <ccc  c="X">3</ccc>
            <ccc  c="X">5</ccc>
      </xxx>
      <yyy>
            <ccc  c="X">3</ccc>
      </yyy>


Previous chapter: Namespaces
Next chapter: Recursions
Previous page: Sequence of several values as the second argument of key function
Next page: Using keys in variables or parameters