xsl:key

  1. key_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1" name="Delta" price="3250" stock="4" country="Denmark"/>
  5.   <product id="p2" name="Golf" price="1000" stock="5" country="Germany"/>
  6.   <product id="p3" name="Alpha" price="1200" stock="19" country="Germany"/>
  7.   <product id="p4" name="Foxtrot" price="1500" stock="5" country="Australia"/>
  8.   <product id="p5" name="Tango" price="1225" stock="3" country="Japan"/>
  9. </products>
  1. key_1-stylesheet.xsl

  2. <?xml version="1.0"?>
  3. <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  4.   <xsl:output indent="yes">
  5.   <xsl:key name="myKey" match="products/product" use="@id"/>
  6.   <xsl:variable name="x" select="'p4'"/>
  7.   <xsl:template match="/">
  8.     <products>
  9.       <product id="{$x}">
  10.         <navn>
  11.           <xsl:value-of select="key('myKey', $x)/@name"/>
  12.         </navn>
  13.         <country>
  14.           <xsl:value-of select="key('myKey', $x)/@country"/>
  15.         </country>
  16.       </product>
  17.     </products>
  18.   </xsl:template>
  19. </xsl:stylesheet>
  1. key_1-output

  2. <?xml version="1.0" encoding="UTF-8"?>
    <products>
      <product id="p4">
        <navn>Foxtrot</navn>
        <country>Australia</country>
      </product>
    </products>

Comment

The element xsl:key works hand in hand with the key() function. If the input file is huge and you have many look-ups, xsl:key can speed up the process many times.

Updated 2009-03-19