Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 · XML, XPath and XSLT

XSLT Basics – Transforming XML

Learn XSLT, the XML transformation language: stylesheets, templates, apply-templates, for-each, value-of, sorting, conditions and output formats, with a runnable template-engine stand-in.

XSLT (eXtensible Stylesheet Language Transformations) converts one XML document into another document: HTML, plain text, or different XML. A transformation is itself written in XML, as a stylesheet of rules. Each rule, called a template, says "when you meet a node like this, output that". XPath, from the last lesson, picks the nodes.

No XSLT processor exists on this site's runner. The stylesheet listings below are read-only real XSLT 1.0, which browsers, xsltproc and Saxon can run. The runnable examples use a small template-driven transformer written in JavaScript as a stand-in, to show the same processing model.

The idea

flowchart LR
  A["Source XML"] --> C["XSLT processor"]
  B["Stylesheet<br/>(templates)"] --> C
  C --> D["Result: HTML, text or XML"]

The processor walks the source tree and applies the best-matching template at each node.

A first stylesheet

Source:

XML
<catalog>
  <book><title>The Little Compiler</title><price>29.90</price></book>
  <book><title>Garden Notes</title><price>12.50</price></book>
</catalog>

Stylesheet:

XML
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes"/>

  <xsl:template match="/catalog">
    <html>
      <body>
        <h1>Our books</h1>
        <ul>
          <xsl:apply-templates select="book"/>
        </ul>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="book">
    <li><xsl:value-of select="title"/> - $<xsl:value-of select="price"/></li>
  </xsl:template>

</xsl:stylesheet>

The result is an HTML page with one list item per book.

The core instructions

Instruction Purpose
xsl:template match="..." a rule for nodes matching an XPath pattern
xsl:apply-templates select="..." process these nodes using the matching templates
xsl:value-of select="..." output the text value of an expression
xsl:for-each select="..." loop over nodes in place
xsl:if test="..." conditional output
xsl:choose / when / otherwise if/else chain
xsl:sort select="..." order the nodes being processed
xsl:attribute, xsl:element build attributes and elements dynamically
xsl:variable, xsl:param named values and parameters
xsl:copy, xsl:copy-of copy nodes, the basis of the identity transform

Literal tags in a template (<li>, <h1>) are copied straight to the output. Inside an attribute of a literal tag you can write an attribute value template: <a href="{@url}"> evaluates the XPath between braces.

for-each, sort and if

XML
<xsl:template match="/catalog">
  <table>
    <xsl:for-each select="book">
      <xsl:sort select="price" data-type="number" order="descending"/>
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td>
          <xsl:if test="price &gt; 20">expensive</xsl:if>
        </td>
      </tr>
    </xsl:for-each>
  </table>
</xsl:template>

Inside an XML attribute, write > as &gt; and < as &lt;, since a stylesheet is XML.

The identity transform

A famous pattern copies everything unchanged, then overrides specific nodes. It is the starting point for edits such as "remove all prices" or "rename an element".

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

<!-- More specific rule: drop every price -->
<xsl:template match="price"/>

A template engine stand-in

The code below mimics the processing model: a table of rules keyed by element name, a process function that applies the matching rule to each node, and an applyTemplates helper. It is a simplified stand-in, not an XSLT engine.

Node.js Template rules transforming XML to HTML (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The structure matches the stylesheet idea: the catalog rule creates the page frame and delegates to the book rule, which formats one item; sorting and a conditional come from the stylesheet logic.

Identity transform with an override (stand-in)

Node.js Copy everything except prices (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

XSLT in the real world

Browsers can apply XSLT 1.0 to XML files that link a stylesheet with <?xml-stylesheet?> (and through XSLTProcessor). Command-line tools such as xsltproc and processors like Saxon (XSLT 3.0) run it in build pipelines, for example turning DocBook into HTML or PDF. Today JSON and JavaScript templates have replaced much of XSLT on the web, but it remains common in publishing, enterprise integration and document conversion.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What language is an XSLT stylesheet written in?

    A stylesheet is an XML document using the xsl namespace.
  2. 2. Which instruction recursively processes selected nodes using matching templates?

    apply-templates selects nodes and hands each to its best-matching template.
  3. 3. How do you write a greater-than comparison inside an attribute of a stylesheet?

    A stylesheet is XML, so characters like < and > should be escaped as entities.
  4. 4. What is the identity transform used for?

    It is the base pattern for edits such as removing or renaming elements.

Summary

  • XSLT transforms XML into HTML, text or other XML using templates written in XML.
  • Templates match nodes with XPath; apply-templates, value-of, for-each, if, choose and sort do the work.
  • The identity transform plus overrides is the standard way to edit documents.
  • Browsers, xsltproc and Saxon run stylesheets; JSON-based tooling replaced XSLT in many web uses.

Next: YAML Syntax Basics