Cover Image for XSLT xsl:key
134 views

XSLT xsl:key

In XSLT (Extensible Stylesheet Language Transformations), the xsl:key element is used to define a named key that can be used for efficient node lookup and grouping during the XSLT transformation process. xsl:key creates an index based on a specified XPath expression, allowing you to quickly access nodes that match that expression.

The xsl:key element is typically defined in the top-level of the XSLT stylesheet and has the following syntax:

<xsl:key name="key-name" match="match-pattern" use="use-expression"/>
  • name: Specifies the name of the key. This name is used to reference the key in other parts of the XSLT stylesheet.
  • match: Defines the pattern for the nodes to be indexed. This is an XPath expression that selects the nodes to be used as keys.
  • use: Defines the expression that generates the key value for each indexed node. The value generated by the use expression is used as the lookup key.

Once you have defined a key, you can use it with the key() function to perform efficient node lookups or groupings based on the key value. The key() function has the following syntax:

key('key-name', 'key-value')
  • key-name: Specifies the name of the key that you defined using xsl:key.
  • key-value: Specifies the value for which you want to retrieve the corresponding nodes.

Here’s an example of using xsl:key to group books by their categories:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:key name="book-by-category" match="book" use="@category" />

  <xsl:template match="/">
    <bookstore>
      <!-- Group books by category -->
      <xsl:for-each select="bookstore/book[generate-id() = generate-id(key('book-by-category', @category)[1])]">
        <category>
          <xsl:attribute name="name"><xsl:value-of select="@category"/></xsl:attribute>
          <xsl:apply-templates select="key('book-by-category', @category)"/>
        </category>
      </xsl:for-each>
    </bookstore>
  </xsl:template>

  <!-- Template to process individual book nodes -->
  <xsl:template match="book">
    <book>
      <title><xsl:value-of select="title"/></title>
      <author><xsl:value-of select="author"/></author>
    </book>
  </xsl:template>
</xsl:stylesheet>

In this example, assuming the XML input contains a list of <book> elements with a “category” attribute, the XSLT transformation groups the books by their categories using the xsl:key named “book-by-category.” It then generates an output that organizes the books into categories.

Using xsl:key can significantly improve the performance of XSLT transformations when you need to perform repeated lookups or groupings based on specific node values. It helps to reduce the complexity of the XSLT code and makes it more efficient when dealing with large XML documents.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS