XSLT <xsl:key> Element

The XSLT element is used to specify a named name-value pair assigned to a specific element in an XML document. This key is used with the key() function in XPath expressions to access the assigned elements in an XML document.

snippet
<xsl:key 
   name = QName 
   match = Pattern 
   use = Expression> 
</xsl:key>

Parameter explanation

Index Name Description
1) Name It specifies the name of the key to be used.
2) Match It specifies that the pattern must be matched to a node that holds this key.
3) Use It specifies XPath expression to identify the value of the nodes of xml document.

XSLT <xsl:key> Element Example

Let's take an example to create a table of <employee> element with its attribute "id"and its child <firstname>, <lastname>, <nickname>, and <salary> by iterating over each employee. This example checks key as firstname to be one of the employee's name and then prints the employee's details.

Employee.xml

snippet
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "employee.xsl"?>
<class> 
   <employee id = "001">
      <firstname>Aryan</firstname> 
      <lastname>Gupta</lastname> 
      <nickname>Raju</nickname> 
      <salary>60000</salary>
   </employee> 
   <employee id = "024"> 
      <firstname>Sonam</firstname> 
      <lastname>Gupta</lastname> 
      <nickname>Vinni</nickname> 
      <salary>45000</salary>
   </employee> 
   <employee id = "056"> 
      <firstname>Peter</firstname> 
      <lastname>Symon</lastname> 
      <nickname>John</nickname> 
      <salary>20000</salary> 
   </employee> 
</class>

Employee.xsl

snippet
<xsl:stylesheet version = "1.0" 
   xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> 
   <xsl:key name = "firstname-search" match = "employee" use = "firstname"/>  
   <xsl:template match = "/">  
      <html>  
         <body>>  
            <h2> Employee</h2>  
            <table border = "1">  
               <tr bgcolor = "pink">  
                  <th> ID</th> 
                  <th>> First Name</th> 
                  <th> Last Name</th>  
                  <th> Nick Name</th>  
                  <th> Salary</th>  
               </tr>>  
     
               <xsl:for-each select = "key('firstname-search', 'Sonam')">  
    
                  <tr> 
                     <td> <xsl:value-of select = "@id"/> </td>  
                     <td> <xsl:value-of select = "firstname"/> </td>  
                     <td> <xsl:value-of select = "lastname"/> ></td>  
                     <td> <xsl:value-of select = "nickname"/> </td>  
                     <td> <xsl:value-of select = "salary"/> </td>  
                  </tr>  
     
               </xsl:for-each>  
            </table>  
        </body>  
      </html>  
   </xsl:template>   
</xsl:stylesheet>

Output:

XSLT Xsl key element 1
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +