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

Key instruction and key function.

Keys are very potent tools in the armory of an XSLT programmer. While it may take some time before mastering the concept, the effort pays off.

Keys are defined using xsl:key element. The name attribute provides a name for the key, the match attribute determines which nodes in the source document will be matched and the use attribute specifies the criterium which decides whether the node matches or not. Function key() then selects nodes based on a key.

In this example the key "kkk" matches all "bbb" elements in the source document. The function key('kkk','a') selects all "bbb" elements which have their attribute "x" equal to 'a' (determined by use).

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="bbb"
                        use="@x"/>

            <xsl:template  match="/aaa">
                  <xsl:apply-templates  select="key('kkk','a')"/>
            </xsl:template>

            <xsl:template  match="bbb">
                  <uuu>
                        <xsl:value-of  select="."/>
                  </uuu>
            </xsl:template>

      </xsl:stylesheet>
XML

      <aaa>
            <bbb  x="a">1</bbb>
            <ccc>
                  <bbb  x="b">2</bbb>
            </ccc>
            <ddd>
                  <eee>
                        <bbb  x="a">3</bbb>
                  </eee>
            </ddd>
      </aaa>
Output

      <uuu>1</uuu>
      <uuu>3</uuu>


Previous chapter: Namespaces
Next chapter: Recursions
Previous page: - - -
Next page: Key matching based on element context