XSLT on the Server
Transform XML documents on the server side
🖥️ What is Server-Side XSLT?
Server-side XSLT transforms XML data into HTML before sending it to browsers. This approach ensures all users receive properly formatted content regardless of browser capabilities.
<!-- XML data on server -->
<books>
<book>
<title>Learning XML</title>
</book>
</books>
Why Use Server-Side XSLT?
Server-side transformation offers better performance and compatibility. The server processes XML and XSLT, then sends ready-to-display HTML to browsers, reducing client workload and ensuring consistent results across all devices.
Better Performance
Server handles heavy processing
Browser Compatible
Works on all browsers
Secure
XML stays on server
Mobile Friendly
Less client processing needed
🔹 PHP Example
Transform XML using PHP on the server:
<?php
// Load XML file
$xml = new DOMDocument;
$xml->load('books.xml');
// Load XSLT file
$xsl = new DOMDocument;
$xsl->load('books.xsl');
// Create XSLT processor
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
// Transform and output
echo $proc->transformToXML($xml);
?>
How it works: PHP loads both XML and XSLT files, processes the transformation, and sends HTML to the browser.
🔹 Node.js Example
Use Node.js to transform XML on the server:
const xslt = require('xslt');
const fs = require('fs');
// Read XML and XSLT files
const xml = fs.readFileSync('books.xml', 'utf8');
const xsl = fs.readFileSync('books.xsl', 'utf8');
// Transform
const html = xslt(xml, xsl);
// Send to client
console.log(html);
Note:
Install the xslt package using:
npm install xslt
🔹 ASP.NET Example
Transform XML using ASP.NET C#:
using System.Xml.Xsl;
// Create transformer
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("books.xsl");
// Transform XML to HTML
xslt.Transform("books.xml", "output.html");
🔹 Complete Server Example
Here's a full example with XML, XSLT, and server code:
📄 books.xml
<?xml version="1.0"?>
<catalog>
<book>
<title>XML Basics</title>
<author>John Doe</author>
<price>29.99</price>
</book>
</catalog>
📄 books.xsl
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Book Catalog</h2>
<xsl:for-each select="catalog/book">
<p><xsl:value-of select="title"/></p>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Server Output (HTML sent to browser):
Book Catalog
XML Basics
🔹 Advantages vs Client-Side
Server-Side Benefits:
- Universal Support: Works on all browsers
- Faster Loading: Browser receives ready HTML
- SEO Friendly: Search engines see HTML content
- Security: XML source code hidden from users
- Caching: Transformed results can be cached