XSLT Apply on the Client

Transforming XML in the browser with XSLT

🌐 What is Client-Side XSLT?

Client-side XSLT transforms XML data directly in the web browser using JavaScript. The browser downloads XML and XSLT files, then applies the transformation to display formatted HTML content dynamically.


// Load and transform XML in browser
xsltProcessor.importStylesheet(xslDoc);
var resultDoc = xsltProcessor.transformToFragment(xmlDoc, document);
                                    

Understanding Client-Side XSLT

Client-side XSLT processing happens in the user's browser using JavaScript. The browser fetches XML and XSLT files, performs the transformation locally, and displays the result. This reduces server load and enables dynamic content updates.

🌐

Browser Processing

Transform in the client

XSLTProcessor()

Dynamic Updates

Real-time transformations

transformToFragment()
📦

Reduced Server Load

Processing on client side

fetch('data.xml')
🔄

Reusable Templates

One XSLT, many uses

importStylesheet()

🔹 Basic Client-Side Example

Transform XML to HTML directly in the browser:

XML File (data.xml):

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<catalog>
    <book>
        <title>XML Basics</title>
        <author>John Doe</author>
        <price>29.99</price>
    </book>
    <book>
        <title>XSLT Guide</title>
        <author>Jane Smith</author>
        <price>34.99</price>
    </book>
</catalog>

XSLT File (style.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>
        <table border="1">
            <tr>
                <th>Title</th>
                <th>Author</th>
                <th>Price</th>
            </tr>
            <xsl:for-each select="catalog/book">
                <tr>
                    <td><xsl:value-of select="title"/></td>
                    <td><xsl:value-of select="author"/></td>
                    <td>$<xsl:value-of select="price"/></td>
                </tr>
            </xsl:for-each>
        </table>
    </body>
    </html>
</xsl:template>

</xsl:stylesheet>

Note: Simply open the XML file in a modern browser. The browser will automatically apply the XSLT transformation specified in the xml-stylesheet processing instruction.

🔹 JavaScript XSLT Transformation

Use JavaScript to load and transform XML programmatically:

HTML File:

<!DOCTYPE html>
<html>
<head>
    <title>XSLT Client Demo</title>
</head>
<body>
    <h1>Book Catalog</h1>
    <div id="result"></div>

    <script>
        // Load XML
        fetch('data.xml')
            .then(response => response.text())
            .then(xmlString => {
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
                
                // Load XSLT
                return fetch('style.xsl')
                    .then(response => response.text())
                    .then(xslString => {
                        const xslDoc = parser.parseFromString(xslString, 'text/xml');
                        
                        // Transform
                        const xsltProcessor = new XSLTProcessor();
                        xsltProcessor.importStylesheet(xslDoc);
                        const resultDoc = xsltProcessor.transformToFragment(xmlDoc, document);
                        
                        // Display
                        document.getElementById('result').appendChild(resultDoc);
                    });
            });
    </script>
</body>
</html>

🔹 Simple JavaScript Example

A minimal working example with inline XML and XSLT:

<!DOCTYPE html>
<html>
<head>
    <title>Simple XSLT Demo</title>
</head>
<body>
    <div id="output"></div>

    <script>
        // XML data as string
        const xmlString = `
            <products>
                <product>
                    <name>Laptop</name>
                    <price>999</price>
                </product>
                <product>
                    <name>Mouse</name>
                    <price>25</price>
                </product>
            </products>
        `;

        // XSLT stylesheet as string
        const xslString = `
            <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
                <xsl:template match="/">
                    <ul>
                        <xsl:for-each select="products/product">
                            <li>
                                <xsl:value-of select="name"/> - 
                                $<xsl:value-of select="price"/>
                            </li>
                        </xsl:for-each>
                    </ul>
                </xsl:template>
            </xsl:stylesheet>
        `;

        // Parse XML and XSLT
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
        const xslDoc = parser.parseFromString(xslString, 'text/xml');

        // Transform
        const xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xslDoc);
        const resultDoc = xsltProcessor.transformToFragment(xmlDoc, document);

        // Display result
        document.getElementById('output').appendChild(resultDoc);
    </script>
</body>
</html>

Output:

  • Laptop - $999
  • Mouse - $25

🔹 Browser Compatibility

XSLT support varies across browsers:

✅ Supported Browsers:

  • Chrome/Edge: Full XSLT 1.0 support
  • Firefox: Excellent XSLT support
  • Safari: Good XSLT 1.0 support

⚠️ Limitations:

  • XSLT 2.0 and 3.0 not supported in browsers
  • Some advanced functions may not work
  • File loading requires a web server (not file://)

🔹 Advantages & Disadvantages

Advantages

  • Reduces server load
  • Faster page updates
  • Separation of data/presentation
  • Reusable stylesheets

Disadvantages

  • Browser compatibility issues
  • SEO challenges
  • Requires JavaScript enabled
  • Limited to XSLT 1.0

🔹 Best Practices

  • Always test across multiple browsers
  • Provide fallback content for non-JavaScript users
  • Use server-side XSLT for SEO-critical content
  • Keep XSLT stylesheets simple for better performance
  • Cache XML and XSLT files when possible
  • Handle errors gracefully with try-catch blocks

🔹 Complete Working Example

A full example with error handling:

<!DOCTYPE html>
<html>
<head>
    <title>XSLT Client Example</title>
    <style>
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #4CAF50; color: white; }
    </style>
</head>
<body>
    <h1>Product Catalog</h1>
    <button onclick="loadData()">Load Products</button>
    <div id="content"></div>

    <script>
        function loadData() {
            try {
                const xmlString = `<catalog>
                    <product><name>Laptop</name><price>999</price></product>
                    <product><name>Mouse</name><price>25</price></product>
                </catalog>`;

                const xslString = `<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
                    <xsl:template match="/">
                        <table>
                            <tr><th>Product</th><th>Price</th></tr>
                            <xsl:for-each select="catalog/product">
                                <tr>
                                    <td><xsl:value-of select="name"/></td>
                                    <td>$<xsl:value-of select="price"/></td>
                                </tr>
                            </xsl:for-each>
                        </table>
                    </xsl:template>
                </xsl:stylesheet>`;

                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
                const xslDoc = parser.parseFromString(xslString, 'text/xml');

                const xsltProcessor = new XSLTProcessor();
                xsltProcessor.importStylesheet(xslDoc);
                const resultDoc = xsltProcessor.transformToFragment(xmlDoc, document);

                document.getElementById('content').innerHTML = '';
                document.getElementById('content').appendChild(resultDoc);
            } catch (error) {
                document.getElementById('content').innerHTML = 
                    '<p style="color: red;">Error: ' + error.message + '</p>';
            }
        }
    </script>
</body>
</html>

💡 Key Points:

  • Client-side XSLT transforms XML in the browser using JavaScript
  • Use XSLTProcessor API for programmatic transformations
  • Requires web server for loading external files (not file://)
  • Limited to XSLT 1.0 in all browsers
  • Best for dynamic content that doesn't need SEO
  • Always include error handling for production code

🧠 Test Your Knowledge

Which JavaScript object is used for client-side XSLT?