XSLT Tutorial – XSLT Transformations & Elements With Examples

This Tutorial Explains What is XSLT, its Transformations, Elements, and Usage with Example. Also covers the Importance of XPath to Develop XSLT Conversion Code:

The term “XSLT” is generated by combining two words i.e. ‘XSL’ and ‘T’, ‘XSL’ is the short form of ‘Extensible Stylesheet Language’ and ‘T’ is a short form of ‘Transformation’.

So, basically, XSLT is a transformation language that is used to transform/convert source XML documents to XML documents or to other formats such as HTML, PDF by using XSL-FO (Formatting Objects), etc.

XSLT Tutorial

Introduction To XSLT

Transformation happens with the help of the XSLT processor (like Saxon, Xalan). This XSLT processor takes one or more XML documents as a source with one XSLT file that contains XSLT code written in it and the result/output documents will get generated later as shown in the below diagram.

XSLT Processor

The XSLT processor parses the source XML documents by using X-Path to navigate over different source elements starting from the root element till the end of documents.

Recommended Reading => All That You Need To Know About X-Path

XSLT Transformation

For starting transformation we need one XML document on which the XSLT code will run, the XSLT code file itself and the tool or software having XSLT processor (You can use any free version or trial version of the software for learning purposes).

#1) XML Code

Below is the source XML code on which the XSLT code will run.

File Name: Books.xml

<?xml version="1.0" encoding="UTF-8"?>
<store> <!-- Root Element -->
    <book id ="5350192956">
        <bookname>XSLT Programmer's Reference</bookname> 
        <authorname>Michael Kay</authorname>
        <publisher>Wrox</publisher>
        <price>$40</price> 
        <edition>4th</edition>         
    </book> 
    <book id ="3741122298">
        <bookname>Head First Java</bookname> 
        <authorname>Kathy Sierra</authorname>
        <publisher>O'reilly</publisher>
        <price>$19</price> 
        <edition>1st</edition>         
    </book>
    <book id ="9987436700">
        <bookname>SQL The Complete Reference</bookname> 
        <authorname>James R. Groff</authorname>
        <publisher>McGraw-Hill</publisher>
        <price>$45</price> 
        <edition>3rd</edition>         
    </book>
</store>

#2) XSLT Code

Below is the XSLT code based on <xsl:for-each> which will run on the above XML Document.

File Name: Books.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">            
        <xsl:template match = "/">           
            <html>   
                <body>  
                    <h2>Books:-</h2>   
                    <table border = "1">   
                        <tr bgcolor = "#cd8932">   
                            <th>Book ID</th>   
                            <th>Book Name</th>   
                            <th>Author Name</th>   
                            <th>Publisher</th>   
                            <th>Price</th>                           
                            <th>Edition</th>
                        </tr>                        
                        <xsl:for-each select="store/book">   
                            <tr bgcolor = "#84cd32">   
                                <td><xsl:value-of select = "@id"/></td>   
                                <td><xsl:value-of select = "bookname"/></td>   
                                <td><xsl:value-of select = "authorname"/></td>   
                                <td><xsl:value-of select = "publisher"/></td>   
                                <td><xsl:value-of select = "price"/></td>                               
                                <td><xsl:value-of select = "edition"/></td>
                            </tr>   
                        </xsl:for-each>   
                    </table>   
                </body>   
            </html>   
        </xsl:template>   
</xsl:stylesheet>

#3) Result / Output Code

The below code will be produced after using the XSLT code on the above XML document.

<html>
   <body>
      <h2>Books:-</h2>
      <table border="1">
         <tr bgcolor="#cd8932">
            <th>Book ID</th>
            <th>Book Name</th>
            <th>Author Name</th>
            <th>Publisher</th>
            <th>Price</th>
            <th>Edition</th>
         </tr>
         <tr bgcolor="#84cd32">
            <td>5350192956</td>
            <td>XSLT Programmer's Reference</td>
            <td>Michael Kay</td>
            <td>Wrox</td>
            <td>$40</td>
            <td>4th</td>
         </tr>
         <tr bgcolor="#84cd32">
            <td>3741122298</td>
            <td>Head First Java</td>
            <td>Kathy Sierra</td>
            <td>O'reilly</td>
            <td>$19</td>
            <td>1st</td>
         </tr>
         <tr bgcolor="#84cd32">
            <td>9987436700</td>
            <td>SQL The Complete Reference</td>
            <td>James R. Groff</td>
            <td>McGraw-Hill</td>
            <td>$45</td>
            <td>3rd</td>
         </tr>
      </table>
   </body>
</html>

#4) View Result / Output in Web Browser

Books:

Book IDBook NameAuthor NamePublisherPriceEdition
5350192956XSLT Programmer's ReferenceMichael KayWrox$404th
3741122298Head First JavaKathy SierraO'reilly$191st
9987436700SQL The Complete ReferenceJames R. GroffMcGraw-Hill$453rd

XSLT Elements

To understand the above XSLT code and it’s working, we first need to understand the different XSLT elements and their attributes.

#1) <xsl:stylesheet> OR<xsl:transform>

Every XSLT code must start with the root element either <xsl:stylesheet> or <xsl:transform>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:xs="http://www.w3.org/2001/XMLSchema" 
version="2.0"> 

Attributes:

  • @xmlns:xsl: Connects XSLT document with XSLT standard.
  • @version: Defines the version of the XSLT code to the parser.

#2) <xsl:template>

This declaration defines a set of rules applied to process or transform the selected input element of the source document to the defined target element rules of the output documents.

Basically two types of templates are available as per their attributes:

(i) Named Template: When the xsl: template element contains @name attribute then this is called Named Template.

<xsl:template name="book">

Named templates are called by xsl:call-template element.

<xsl:call-template name="book">

(ii) Match Template: The xsl:template element contains @match attribute that contains a matching pattern or XPath applied at the input nodes.

<xsl:template match="//book">

Match templates are called by xsl:apply-template element.

<xsl:apply-templates select="book"/>

xsl:template element must have either@match attribute or @name attribute or both. An xsl:template element that has no match attribute must have no mode attribute and no priority attribute.

Let’s re-write the above XSLT(<xsl:for-each) code with respect to Named Template(@name) and Match Template(@match).

a) XSLT code based on Match Template with <xsl:apply-template>. See below yellow & grey highlighted changed code, it will produce the same above output result.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">            
    <xsl:template match = "/">           
        <html>   
            <body>  
                <h2>Books:-</h2>   
                <table border = "1">   
                    <tr bgcolor = "#cd8932">   
                        <th>Book ID</th>   
                        <th>Book Name</th>   
                        <th>Author Name</th>   
                        <th>Publisher</th>   
                        <th>Price</th>                           
                        <th>Edition</th>
                    </tr>      
                    <xsl:apply-templates select="store"/>
                </table>   
            </body>   
        </html>   
    </xsl:template>
    <xsl:template match="store">
        <xsl:apply-templates select="book"/>
    </xsl:template>
    
    <xsl:template match="book">
        <tr bgcolor = "#84cd32">  
            <td><xsl:value-of select = "@id"/></td>   
            <td><xsl:value-of select = "bookname"/></td>   
            <td><xsl:value-of select = "authorname"/></td>   
            <td><xsl:value-of select = "publisher"/></td>   
            <td><xsl:value-of select = "price"/></td>                               
            <td><xsl:value-of select = "edition"/></td>
        </tr>  
    </xsl:template>
</xsl:stylesheet>

Refer the screenshot for highlighted area:

Match Template

b) XSLT code based on the Named Template with <xsl:call-template>. See below yellow & grey highlighted changed code, it will produce the same above output result.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">            
    <xsl:template match = "/">           
        <html>   
            <body>  
                <h2>Books:-</h2>   
                <table border = "1">   
                    <tr bgcolor = "#cd8932">   
                        <th>Book ID</th>   
                        <th>Book Name</th>   
                        <th>Author Name</th>   
                        <th>Publisher</th>   
                        <th>Price</th>                           
                        <th>Edition</th>
                    </tr>                        
                    <xsl:for-each select="store/book">  
                        <xsl:call-template name="book"/>                       
                    </xsl:for-each>   
                </table>   
            </body>   
        </html>   
    </xsl:template>
    <xsl:template name="book">
        <tr bgcolor = "#84cd32"> 
            <td><xsl:value-of select = "@id"/></td>   
            <td><xsl:value-of select = "bookname"/></td>   
            <td><xsl:value-of select = "authorname"/></td>   
            <td><xsl:value-of select = "publisher"/></td>   
            <td><xsl:value-of select = "price"/></td>                               
            <td><xsl:value-of select = "edition"/></td>
        </tr>
    </xsl:template>

Refer the screenshot for highlighted area:

XSLT code based on Named Template

#3) <xsl:apply-templates>

The processor will find and apply all the templates that are having XPath defined in the @select attribute.

xsl apply-templates

The @mode attribute is also used if we want to give more than one way of output with the same input content.

#4) <xsl:call-template>

The processor will make a call to the templates having value inside the @name attribute (required).

xsl call-template

<xsl:with-param> element is used to pass parameters to the template.

#5) <xsl:value-of>

Provide the string/text value regarding the XPath expression defined in the @select attribute, as defined in the above code.

<xsl:value-of select = "bookname"/>

This will give the value of the book name.

#6) <xsl:for-each>: Repetition

This will process the instructions for each set of nodes (xpath defined in @select (required) attribute) in the sorted sequence.

<xsl:for-each select="store/book">

The above code means for each node set of store/book means:

/store/book[1]
/store/book[2]
/store/book[3]
<xsl:sort> can also be used as a child of xsl:for-each to define the order of sorting.

#7) <xsl:if>: Conditional Processing

The xsl:if instructions will only process if the Boolean value of the @test attribute will be true otherwise the instruction will not be evaluated and the empty sequence is returned.

<xsl:if test="count(/store/book)>2">
                            <xsl:text>
                                Condition True: Count of books are more than two.
                            </xsl:text>
           </xsl:if>

Result: Condition True: Count of books are more than two.

Here the count() is the predefined function.

#8) <xsl:choose>: Alternatives condition processing

xsl:choose have multiple cases for different conditions that are tested inside @test attribute of the xsl:when elements, the test condition which comes true first among all the xsl:when, that will be processed first and there are an optional xls:otherwise element so that if none of the condition tests come true then this xsl:otherwise will be considered.

<xsl:choose>
                           <xsl:when test="count(/store/book)=1">
                                Condition True: Count of book is one.
                            </xsl:when>
                            <xsl:when test="count(/store/book)=2">
                                Condition True: Count of book is two.
                            </xsl:when>
                            <xsl:when test="count(/store/book)=3">
                                Condition True: Count of book is three.
                            </xsl:when>
                            <xsl:otherwise>
                                No condition match.
                            </xsl:otherwise>
              </xsl:choose>

Result: Condition True: Count of the book is three.

#9) <xsl:copy>

xsl:copy works on context item i.e. if that is node then it will copy the context node to the newly generated node and this will not copy the children of the context node. Because of this reason, this is called a shallow copy. Unlike xsl:copy-of element, the xsl:copy does not have the@select attribute.

In the below code, the context items are copied to output & all the children items are called & copied by the xsl:apply-template recursively.

node()|@* Stands for all the nodes and all their attributes recursively.

<xsl:template match="node()|@*">
        		<xsl:copy>
           	 <xsl:apply-templates select="node()|@*"/>
        		</xsl:copy>
    		</xsl:template>

Result: This will copy all the nodes and attributes of the source document recursively to the output document, i.e. it will create an exact copy of the source document.

#10) <xsl:copy-of>

xsl:copy-of will copy the sequence of nodes with all of its children and attributes recursively by default, due to this nature this is also called as deep copying. @select attribute is required for the evaluation of the XPath.

<xsl:template match="node()|@*">
        		<xsl:copy-of select="."/>
    		</xsl:template>

Result: This will copy all the nodes and attributes of the source document recursively to the output document, i.e. it will create an exact copy of the source document.

<xsl:copy-of select="."/>

Stands for a copy of the current node and current attribute.

#11) <xsl:comment>

This element is used to write a comment to the target result, any text content that is side this tag will be printed as commented output.

<xsl:comment> This will be printed to output as comment node.</xsl:comment>

Result:<!– This will be printed to output as comment node.–>

#12) <xsl:text>

This will generate a text node to the result document, the value inside the xsl:text will get printed as a string to output.

<xsl:text>
This is a
text line.
</xsl:text>

Output:

This is a
text line.

#13) <xsl:element>

This will generate an element to the result document with the name mentioned in its @name attribute. The name attribute is the required attribute.

<xsl:template match="/">
      		<xsl:element name="bookcode">
          		<xsl:value-of select="/store/book[1]/@id"/>
      		</xsl:element>
    		</xsl:template>

Result: <bookcode>5350192956</bookcode>

#14) <xsl:attribute>

This will generate an attribute to its parent element in the result document. The name of the attribute is defined by the name attribute and the value of the attribute is computed by the XPath mentioned in the select attribute as given in the below code. The name attribute is the required attribute.

<xsl:template match="/">
      		<xsl:element name="bookcode">
          		<xsl:attribute name="id" select="/store/book[1]/@id"/>
      		</xsl:element>
    		</xsl:template>

Result: <bookcode id=”5350192956″/>

#15) <xsl:sort>

This element will sort the selected node in a sequence manner accordingly in ascending or descending direction. The node or XPath is given through @select attribute and the direction of sorting is defined by the @order attribute.

In the below code we will get all books list as per the book name in an alphabetic order.

<xsl:template match = "/">           
            	<html>   
                	<body>  
                   	 <h2>Books:-</h2>   
                    	<table border = "1">   
                        <tr bgcolor = "#cd8932">   
                            <th>Book ID</th>   
                            <th>Book Name</th>   
                            <th>Author Name</th>   
                            <th>Publisher</th>   
                            <th>Price</th>                           
                            <th>Edition</th>
                        </tr>                        
                        <xsl:for-each select="store/book">
                            <xsl:sort select="./bookname" order="ascending"/>
                            <tr bgcolor = "#84cd32">   
                                <td><xsl:value-of select = "@id"/></td>   
                                <td><xsl:value-of select = "bookname"/></td>   
                                <td><xsl:value-of select = "authorname"/></td>   
                                <td><xsl:value-of select = "publisher"/></td>   
                                <td><xsl:value-of select = "price"/></td>                               
                                <td><xsl:value-of select = "edition"/></td>
                            </tr>   
                        </xsl:for-each>
                    	</table>   
               	 </body>   
           	 </html>   
        		</xsl:template>

Refer this screenshot for the highlighted area:

xsl sort

Result: The below list contains the book names in an alphabetic order i.e. in ascending order.

Books:

Book IDBook NameAuthor NamePublisherPriceEdition
3741122298Head First JavaKathy SierraO'reilly$191st
9987436700SQL The Complete ReferenceJames R. GroffMcGraw-Hill$453rd
5350192956XSLT Programmer's ReferenceMichael KayWrox$404th

#16) <xsl:variable>

This element declares a variable that holds a value in it. A variable could be a global variable or local variable. The name of the variable is defined by the @name attribute and the value that this variable will hold is defined by the @select attribute.

The access of the global variable is global i.e. the variables can be called within any element and remain accessible within the stylesheet.

To define a global variable, we just need to declare that next to the root element of the stylesheet as shown in the below code in the yellow highlighted, the variable ‘SecondBook’ is the global variable and it holds the name of the second book.

The access of the local variable is local to the element in which it is defined i.e. that variable would not be accessible outside the element in which it is defined as shown in the below code that is grey highlighted, the variable ‘first book’ is a local variable and it holds the name of the first book.

To make a call to either the global variable to the local variable the Dollar symbol ($) is used before the name of the variable, as shown below in yellow highlighted $.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">            
    <xsl:variable name="Secondbook" select="/store/book[2]/bookname[1]"/> 	
<!-- Global Variable -->
    <xsl:template match="/">
        <xsl:variable name="Firstbook" select="/store/book[1]/bookname[1]"/> 	
<!-- Local Variable -->
        <xsl:text>
            First Book Name: </xsl:text>
        <xsl:value-of select="$Firstbook"/>
        <xsl:text>
            Second Book Name: </xsl:text>
        <xsl:value-of select="$Secondbook"/>
    </xsl:template> 
</xsl:stylesheet>
 

Refer the screenshot for the highlighted area:

xsl variable

Result:

First Book Name: XSLT Programmer’s Reference
Second Book Name: Head First Java

#17) <xsl:Key>

This element is used to declare keys, for the matching pattern values to that particular key.

Name is a provider to that key by @name attribute(“get-publisher“), which is later used inside the key() function. @match attribute is provided to index input node by XPath expressions(“book“), like in the below yellow highlighted @match is used to index on all the books available in the store.

Relative to @match attribute, the @use attribute is used, it declares the node to get the value for that key through XPath expression(“publisher”).

xslkey

Now, suppose if we need the details of the book which is published only by ‘Wrox’ publisher then we can get that value easily through xsl:key element by making a key-value pair.

key(‘get-publisher’, ‘Wrox’) Key() takes two parameters, first is the name of the key, which in this case is ‘get-publisher’, second is the string value that needs to search which in our case is ‘Wrox’.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:key name = "get-publisher" match = "book" use = "publisher"/> 
    <xsl:template match = "/">           
        <html>   
            <body>  
                <h2>Books:-</h2>   
                <table border = "1">   
                    <tr bgcolor = "#cd8932">   
                        <th>Book ID</th>   
                        <th>Book Name</th>   
                        <th>Author Name</th>   
                        <th>Publisher</th>   
                        <th>Price</th>                           
                        <th>Edition</th>
                    </tr>                        
                    <xsl:for-each select = "key('get-publisher', 'Wrox')"> 
                        <tr bgcolor = "#84cd32">   
                            <td><xsl:value-of select = "@id"/></td>   
                            <td><xsl:value-of select = "bookname"/></td>   
                            <td><xsl:value-of select = "authorname"/></td>   
                            <td><xsl:value-of select = "publisher"/></td>   
                            <td><xsl:value-of select = "price"/></td>                               
                            <td><xsl:value-of select = "edition"/></td>
                        </tr>   
                    </xsl:for-each>
                </table>   
            </body>   
        </html>   
    </xsl:template>   
</xsl:stylesheet>

Refer the screenshot for the highlighted area:

case is ‘Wrox’

Result:

<html>
   <body>
      <h2>Books:-</h2>
      <table border="1">
         <tr bgcolor="#cd8932">
            <th>Book ID</th>
            <th>Book Name</th>
            <th>Author Name</th>
            <th>Publisher</th>
            <th>Price</th>
            <th>Edition</th>
         </tr>
         <tr bgcolor="#84cd32">
            <td>5350192956</td>
            <td>XSLT Programmer's Reference</td>
            <td>Michael Kay</td>
            <td>Wrox</td>
            <td>$40</td>
            <td>4th</td>
         </tr>
      </table>
   </body>
</html>

Result / HTML View:

Books:

Book IDBook NameAuthor NamePublisherPriceEdition
5350192956XSLT Programmer's ReferenceMichael KayWrox$404th

#18) <xsl:message>

This element is used for debugging purposes in XSLT development. The element gives its output to the standard output screen of the application.

The @terminate attribute is used with two values either ‘yes’ or ‘no’, if the value is set to ‘yes’ then the parser terminates immediately as soon the test condition gets satisfied for the message to get executed.

To understand this, let’s suppose if in our input document the price element comes to empty accidentally as like in the below code, then the processing should stop immediately as soon as the processor encounters the empty price element which can be easily achieved by using xsl:message inside the if test condition as in the below XSLT code.

Debugger alert is shown by the application standard screen: Processing terminated by xsl:message at line 21.

Input XML code:

<book id ="9987436700">
        	<bookname>SQL The Complete Reference</bookname> 
        	<authorname>James R. Groff</authorname>
        	<publisher>McGraw-Hill</publisher>
       	 <price></price> 
        	<edition>3rd</edition>         
    	</book>

Refer screenshot for highlighted area:

xml input code

XSLT Code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:template match = "/">           
        <html>   
            <body>  
                <h2>Books:-</h2>   
                <table border = "1">   
                    <tr bgcolor = "#cd8932">   
                        <th>Book ID</th>   
                        <th>Book Name</th>   
                        <th>Author Name</th>   
                        <th>Publisher</th>   
                        <th>Price</th>                           
                        <th>Edition</th>
                    </tr>                        
                    <xsl:for-each select="store/book">
                        <xsl:if test = "price = ''"> 
                            <xsl:message terminate = "yes">
                              Terminating: price element is empty. 
                            </xsl:message> 
                        </xsl:if> 
                        <tr bgcolor = "#84cd32">   
                            <td><xsl:value-of select = "@id"/></td>   
                            <td><xsl:value-of select = "bookname"/></td>   
                            <td><xsl:value-of select = "authorname"/></td>   
                            <td><xsl:value-of select = "publisher"/></td>   
                            <td><xsl:value-of select = "price"/></td>                               
                            <td><xsl:value-of select = "edition"/></td>
                        </tr>   
                    </xsl:for-each>
                </table>   
            </body>   
        </html>   
    </xsl:template>   
</xsl:stylesheet>

Refer screenshot for highlighted area:

xslt code

Result: Please note that as soon the parser encounters the empty price tag, it immediately terminates the processing because of which the closing tags of </table>, </body> and </html> would not come at the end of the file.

<html>
  		 <body>
      			<h2>Books:-</h2>
     			 <table border="1">
         		 <tr bgcolor="#cd8932">
            			<th>Book ID</th>
            			<th>Book Name</th>
            			<th>Author Name</th>
            			<th>Publisher</th>
            			<th>Price</th>
           			 <th>Edition</th>
        		 </tr>
         		 <tr bgcolor="#84cd32">
            			<td>5350192956</td>
            			<td>XSLT Programmer's Reference</td>
            			<td>Michael Kay</td>
            			<td>Wrox</td>
            			<td>$40</td>
            			<td>4th</td>
        		 </tr>
         		 <tr bgcolor="#84cd32">
            			<td>3741122298</td>
            			<td>Head First Java</td>
           			 <td>Kathy Sierra</td>
           			 <td>O'reilly</td>
            			<td>$19</td>
            			<td>1st</td>
         		</tr>

Refer screenshot for highlighted area:

Xslt code result

#19) <xsl:param>&<xsl:with-param>

<xsl:param> element defines the parameter to template if defined inside <xsl:template>. It can be defined either inside <xsl:stylesheet> as the global parameter or inside <xsl:template> as the local parameter to that template.

The value of the <xsl:param> is passed/supplied when the template is called by <xsl:call-template> or <xsl:apply-templates>.

element define parameter

<xsl:with-param> it passes the value of the parameter defined inside <xsl:param> to the template. Attribute like @name contains the name of the parameter which should match the @name attribute of the <xsl:param> element. @Select attribute is used to set a value to that parameter.

Select attribute

To fetch the value of the parameter same like a variable dollar sign($) is used.

variable dollar sign

Source XML Code:

<store> <!-- Root Element -->
    <book id ="5350192956">
        <bookname>XSLT Programmer's Reference</bookname> 
        <authorname>Michael Kay</authorname>
        <publisher>Wrox</publisher>
        <price>$40</price> 
        <edition>4th</edition>         
    </book> 
    <book id ="3741122298">
        <bookname>Head First Java</bookname> 
        <authorname>Kathy Sierra</authorname>
        <publisher>O'reilly</publisher>
        <price>$19</price> 
        <edition>1st</edition>         
    </book>
    <book id ="9987436700">
        <bookname>SQL The Complete Reference</bookname> 
        <authorname>James R. Groff</authorname>
        <publisher>McGraw-Hill</publisher>
        <price>$45</price> 
        <edition>3rd</edition>         
    </book>
</store>

XSLT Code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">  
    <xsl:template match="/">
        <html>   
            <body>  
                <h2>List of Books Name :-</h2>
                <xsl:for-each select="/store/book">
                    <p>
                    <xsl:call-template name="book_name">
                        <xsl:with-param name="BookName" select="bookname"/>
                    </xsl:call-template>
                    </p>
                </xsl:for-each>
            </body>
        </html>        
    </xsl:template>   
    <xsl:template name="book_name">
        <xsl:param name="BookName"/>
        <xsl:text>
            Book Name: </xsl:text><xsl:value-of select="$BookName"/>
    </xsl:template>  
</xsl:stylesheet>

Refer screenshot for the highlighted area:

XSLT code param bookname

Result Output:

<html>
   <body>
      <h2>List of Books Name :-</h2>
      <p>
         Book Name: XSLT Programmer's Reference
      </p>
      <p>
         Book Name: Head First Java
      </p>
      <p>
         Book Name: SQL The Complete Reference
      </p>
   </body>
</html

#20) <xsl:import>

<xsl:import> is used to import another stylesheet module inside our current stylesheet. This helps in achieving a modular XSLT development approach.

After importing all the templates get available to use. The priority of the templates defined in the parent stylesheet(which is importing another stylesheet) is higher than the imported stylesheet (which is imported by the parent stylesheet).

If another stylesheet also has the same name template as defined inside the template that is importing then the foreign templates get overridden by your own template.

Attribute @href is used as the URI of the stylesheet that you want to import.

<xsl:import href="New_Book.xsl"/>

#21) <xsl:include>

Same as the above xsl:import, <xsl:include> also helps in achieving modular XSLT development approach. All the templates included by <xsl:include> have the same priority/precedence as of the calling stylesheet. It is like you copy all the templates from another stylesheet to your own stylesheet.

Attribute @href is used as the URI of the stylesheet that you want to import.

<xsl:include href="New_Book.xsl"/>

#22)<xsl:output>

This element is used to specify the result tree in the output file. It contains attributes like @method that can have values like ‘XML’, ‘HTML’, ‘XHTML’ and ‘text’ by default is ‘XML’.

@encoding specifies the character encoding that comes in the output file as shown in below example encoding=”UTF-16″, the default values for XML or XHTML could be either UTF-8 or UTF-16. @indent specifies the indentation of the XML or HTML output code, for XML the default value is ‘no’ and for HTML and XHTML the default value is yes.

<xsl:output method="xml" encoding="UTF-16" indent="yes"/>

#23) <xsl:strip-space>

This element is used for stripping(removing) non-significant whitespace for the listed source element inside the @element attribute and if we want to strip whitespace from all the element then we can use ‘*’ inside @elements attribute.

<xsl:strip-space elements="*"/>

#24) <xsl:preserve-space>

This element is used to preserve white spaces for the listed source element inside the @element attribute and if we want to preserve whitespace from all the elements, then we can use ‘*’ inside @elements attribute.

<xsl:preserve-space elements="*"/>

Conclusion

Thus in this article, we have learned about XSLT, frequently used XSLT elements, their usage with example source and target/result code, conversion or transformation of the source element to target element.

We also discussed the importance of XPath to develop XSLT conversion code. We have seen the XSL template declaration and template calling & passing parameters. We learned to declare global and local variables, their usage in the XSLT code and how to call them.

We learnt about different branching or conditional XSLT elements like xsl:if, xsl:for-each, xsl:choose. We understood the difference between shallow copying and deep copying, sorting of nodes, debugging of XSLT code by using xsl:message, the difference between named template and match templates, and output formatting by using xsl:output.

About the Author: Himanshu P. is an experienced professional in the field of Information Technology. He has worked with ITC MNCs on cross-business domains and multiple technologies. Himanshu’s favorite pastime is reading magazines and blogging.