Menu

Monday, August 8, 2011

XSLT

XSL stands for "Extended style sheet". It is a style sheet for xml file.

XSLT stands for "XSL for Transformations".  It is a tool to transform XML document into an Html document or into other type of XML documents.

In the below example, the xml file is transformed into an HTML file using the XSL file.

Here is a sample XML file which describes the books and its author.
 
<books>
 <book price="$35" author="Kathy Sierra">The Head First EJB</book>
 <book price="$18" author="Martin Fowler">UML Distilled </book>
 <book price="$27" author="Bill Dudney">Mastering Java Server Faces </book>
</books>
 

Consider we want to translate the above XML into below Html file.
 
<html>
 <head></head>
 <body>
 <div id="books">
  <ul>
   <li><b>The Head First EJB:</b> $35 : Kathy Sierra</li>
   <li><b>UML Distilled: $18 :</b> Martin Fowler </li>
   <li><b>Mastering Java Server Faces:</b> $27 : Bill Dudney </li>
  </ul>
 </div>
 <body>
</html>
 

Here is the XSLT file which converts the XML file into above HTML format.
 
<?xml version="1.0"?>

<!-- Include this tag, so that it will be identified as a XSL stylesheet -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<!--This tag tells that the output should be transformed into Html-->
<xsl:output method="html"/>

<!-- This template processes the root node i.e / -->
<xsl:template match="/">
 <html>
 <head>
  <title>My Favourite Books</title>
 </head>
 <body>
  <div id="books">
   <ul>
    <!-- Apply a template to process each book tag -->
    <xsl:apply-templates select="books/book"/>
   </ul>
  </div>
 </body>
 </html>
</xsl:template>

<!-- Template to process book tag -->
<xsl:template match="book">
 <li>
  <!-- Get the value of the text node -->
  <b><xsl:value-of select="." /> :</b>
  <!-- Get the value of the price attribute -->
  <xsl:value-of select="@price" /> :
  <!-- Get the value of the author attribute -->
  <xsl:value-of select="@author" /> 
 </li>
</xsl:template>
</xsl:stylesheet>