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.

   name = QName 
   match = Pattern 
   use = Expression> 

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.


<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "employee.xsl"?>
   <employee id = "001">
   <employee id = "024"> 
   <employee id = "056"> 


<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 = "/">  
            <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>  
               <xsl:for-each select = "key('firstname-search', 'Sonam')">  
                     <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>  


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 #