XSLT (Extensible Stylesheet Language Transformations) is a powerful, functional programming language used to transform XML documents into other formats, such as HTML, plain text, PDF, or even a different XML structure.
If XML is the data, XSLT is the engine that reshapes that data for the end user.
XSLT uses XPath to navigate through the XML tree. The process involves three main components:
Source Document: The original XML containing the raw data.
XSLT Stylesheet: The file containing the "rules" for transformation.
XSLT Processor: The software (like Saxon, Libxslt, or even your Web Browser) that merges the two to produce the output.
An XSLT file is itself an XML document. It begins with a declaration and uses specific tags to define the transformation logic.
<xsl:template>: The most important tag. It defines a "rule" to apply when a specific part of the XML is found.
<xsl:value-of>: Extracts the text content of an XML element.
<xsl:for-each>: Loops through every instance of a specific tag (like rows in a table).
<xsl:if> and <xsl:choose>: Conditional logic (if/then/else).
<xsl:apply-templates>: Tells the processor to look for other rules to apply to the children of the current tag.
Unlike Python or Java, XSLT is a declarative, functional language.
No Variables (mostly): Once a "variable" is set in XSLT, its value generally cannot be changed (immutable).
Template Matching: Instead of writing a long script that runs from top to bottom, you define templates that "fire" whenever the processor hits a matching piece of data.
While modern web development often uses JavaScript (React/Vue) to handle data, XSLT is still vital for:
Document Publishing: Converting XML manuals or books into high-quality PDFs or E-books.
B2B Data Integration: Converting a "Company A" invoice format into a "Company B" shipping format automatically.
SEO & Speed: Performing transformations on the server side so the browser receives a finished HTML page, which is faster for search engine indexing.
Legacy Systems: Many banking and insurance back-ends rely on XSLT to generate reports from massive XML databases.
Let's transform a simple list of products into an HTML table.
The Source XML (products.xml):
XML
<inventory>
<item>
<name>Laptop</name>
<price>900</price>
</item>
<item>
<name>Mouse</name>
<price>25</price>
</item>
</inventory>
The XSLT Stylesheet (style.xsl):
XML
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Product List</h2>
<table border="1">
<tr><th>Product Name</th><th>Price</th></tr>
<xsl:for-each select="inventory/item">
<tr>
<td><xsl:value-of select="name"/></td>
<td>$<xsl:value-of select="price"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>