XSLT - <xsl:template>

1. What <xsl:template> Is

  • An XSLT stylesheet is made up of multiple templates.

  • A <xsl:template> tells the processor:
    “When you find a node in the XML that matches this rule, apply these transformation instructions.”

  • You define what to output (HTML, text, or XML) when a certain node in the input XML matches the template’s match pattern.


2. Structure

<xsl:template match="XPath_expression">
    <!-- Transformation instructions -->
</xsl:template>
  • match: an XPath expression that selects nodes in the source XML.

  • Inside the template, you put instructions (xsl:value-of, xsl:for-each, HTML tags, etc.) that describe what to output.


3. Basic Example

XML input:

<book>
  <title>1984</title>
  <author>George Orwell</author>
</book>

XSLT stylesheet:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <!-- Template for the root (/) -->
  <xsl:template match="/">
    <html>
      <body>
        <!-- Apply template for <book> -->
        <xsl:apply-templates select="book"/>
      </body>
    </html>
  </xsl:template>

  <!-- Template for <book> -->
  <xsl:template match="book">
    <h2><xsl:value-of select="title"/></h2>
    <p>Author: <xsl:value-of select="author"/></p>
  </xsl:template>

</xsl:stylesheet>

Output (HTML):

<html>
  <body>
    <h2>1984</h2>
    <p>Author: George Orwell</p>
  </body>
</html>

4. Key Points About <xsl:template>

  1. Root template (match="/")

    • Usually the entry point. It matches the root of the XML document.

  2. Multiple templates

    • You can have many templates, each handling a different XML element.

  3. xsl:apply-templates

    • Used inside one template to tell the processor:
      “Go find matching templates for child elements and apply them.”

  4. Specific vs. Generic

    • You can write specific templates (e.g., match="book/title") or generic ones (e.g., match="*" for all elements).


5. Another Quick Example

XML:

<library>
  <book>1984</book>
  <book>Brave New World</book>
</library>

XSLT:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:template match="/">
    <ul>
      <xsl:apply-templates/>
    </ul>
  </xsl:template>

  <xsl:template match="book">
    <li><xsl:value-of select="."/></li>
  </xsl:template>

</xsl:stylesheet>

Output:

<ul>
  <li>1984</li>
  <li>Brave New World</li>
</ul>