XSLT Template

XSLT <xsl:template> Element

A single or multiple set of rules are present in an XSL style sheet, also called templates. The rules to apply when a specified node is matched, is included in a template.

The <xsl:template> Element:

To build templates, the <xsl:template> element is used and to associate a template with an XML element, the match attribute is used. Again, to define a template for the entire XML document, the match attribute can be used. An XPath expression makes the value of the match attribute, i.e., match=”/” defines the whole document.

Example:

Books.xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
 
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
    <year>2020</year>
    <price>100.00</price>
  </book>
 
  <book category="IT">
    <title lang="en">XQuery Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
    <year>2020</year>
    <price>300.00</price>
  </book>
 
</bookstore>

XSLT Code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html> 
<body>
  <h2>List of Books</h2>
  <table border="1">
    <tr bgcolor="#9acd32">
      <th>Title</th>
      <th>Price</th>
    </tr>
    <tr>
      <td>.</td>
      <td>.</td>
    </tr>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Output:

Explanation:

Being an XML document, an XSL stylesheet always begins with the XML declaration, i.e., <?xml version=”1.0″ encoding=”UTF-8″?>. Now, to specify that a document is an XSLT stylesheet document along with the version number and XSLT namespace attributes, the <xsl:stylesheet> is used. The template is defined using the <xsl:template> element, while to associate the template with the root of the XML source document, the match=”/” attribute is used. Again, to specify some HTML to write to the output, the content inside the <xsl:template> element takes the job. The end of the template and the end of the style sheet is marked by the last two lines.

Please Share