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

Function key() inside an XPath expression

key() function can be used as a step inside XPath expressions. In this example the XPath expression leads to nodes kkk which are then used as the second arguments of the key function. This function then returns a sequence of nodes matching keys "Z" and "X" in document order.

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/ddd/kkk/key('kkk',.)"/>
            </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>
                        <kkk>Z</kkk>
                  </ddd>
            </bbb>
            <bbb  id="b2">
                  <eee>
                        <fff>
                              <ccc  c="Z">3</ccc>
                              <ccc  c="X">4</ccc>
                              <ccc  c="Z">5</ccc>
                        </fff>
                  </eee>
                  <ddd>
                        <kkk>X</kkk>
                  </ddd>
            </bbb>
      </aaa>
Output

      <ccc  c="X">1</ccc>
      <ccc  c="Z">3</ccc>
      <ccc  c="X">4</ccc>
      <ccc  c="Z">5</ccc>


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