XSLT Basics: Templates, Match/Select, and HTML Output
Unit 4âĸCLO04
Learning Objectives
Course Learning Outcomes
CLO04
Course Outcomes
CO04
âšī¸
Introduction
XSLT is a rule-driven language that walks an XML tree with XPath and emits another document (HTML, text, XML, PDF via FO). Mastering templates and context selection is the gateway to clean transformations.
Study tracker
Mark what you have completed for this topic.
0% done
The Basics
Core ideas
- Templates match nodes; matching sets the current context.
- apply-templates delegates processing; value-of pulls text.
- for-each iterates when you need full control over ordering.
- output method controls whether you emit XML, HTML, or text.
Technical Details
Minimal, exam-ready stylesheet
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<html><body>
<h1>Library</h1>
<xsl:apply-templates select="library/book"/>
</body></html>
</xsl:template>
<xsl:template match="book">
<p><xsl:value-of select="title"/></p>
</xsl:template>
</xsl:stylesheet>
Sorting inside for-each:
<xsl:for-each select="library/book">
<xsl:sort select="number(price)" data-type="number" order="descending"/>
<xsl:value-of select="title"/>
</xsl:for-each>
Examples
Input vs output
Input XML
<library>
<book id="b1"><title>XML</title><price>499</price></book>
</library>
HTML output (simplified)
<h1>Library</h1>
<p>XML</p>
Self-check
Real-World Use
Build a starter transform
- Generate an HTML table from book.xml.
- Add a header row with <th>.
- Sort by price descending using xsl:sort.
- Validate that the XSLT runs in a browser or xsltproc.
đ For exams
Exam prompts
- Difference between match and select.
- Role of apply-templates vs for-each.
- What does xsl:output method="html" do?
⨠Key points
Takeaways
- Think in templates; keep the root template small.
- Use apply-templates for extensibility; reach for for-each when you must control order explicitly.
- Sorting and formatting are driven by XPath expressions.