XML and XSLT

Welcome to The Coding College, where we make complex programming concepts easy to understand! In this tutorial, we’ll dive into XML and XSLT (Extensible Stylesheet Language Transformations)—a powerful combination for transforming XML data into various formats like HTML, plain text, or even other XML structures.

What is XSLT?

XSLT (Extensible Stylesheet Language Transformations) is a language used for transforming XML documents into other formats. It uses XSL (Extensible Stylesheet Language) to define rules for the transformation process.

Why Use XSLT?

  1. Customizable Output: Transform XML data into readable formats such as HTML or JSON.
  2. Platform Independence: XSLT is supported in most modern browsers and programming languages.
  3. Separation of Content and Presentation: XML stores raw data, while XSLT defines how it should be displayed or restructured.

How XSLT Works

The transformation process involves three components:

  1. XML Document: The raw data source.
  2. XSLT Stylesheet: The set of rules defining the transformation.
  3. XSLT Processor: Applies the rules to the XML document and generates the output.

Example XML Document

<library>
    <book id="1">
        <title>XML Basics</title>
        <author>John Doe</author>
        <price>19.99</price>
    </book>
    <book id="2">
        <title>Advanced XML</title>
        <author>Jane Smith</author>
        <price>29.99</price>
    </book>
</library>

Writing an XSLT Stylesheet

An XSLT stylesheet is an XML document that contains transformation instructions. It uses the <xsl:template> element to define rules for matching and transforming XML elements.

Example XSLT Stylesheet

This XSLT transforms the <library> XML into an HTML table.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
                <h1>Library Books</h1>
                <table border="1">
                    <tr>
                        <th>Title</th>
                        <th>Author</th>
                        <th>Price</th>
                    </tr>
                    <xsl:for-each select="library/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>

Applying XSLT to XML

Using a Browser

Most modern browsers support XSLT. You can link an XML file to an XSLT stylesheet using the <?xml-stylesheet?> processing instruction.

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="library.xsl"?>
<library>
    <book id="1">
        <title>XML Basics</title>
        <author>John Doe</author>
        <price>19.99</price>
    </book>
    <book id="2">
        <title>Advanced XML</title>
        <author>Jane Smith</author>
        <price>29.99</price>
    </book>
</library>

Opening this XML file in a browser will apply the library.xsl stylesheet and display the transformed output.

Using Python

Python’s lxml library can process XSLT transformations programmatically.

from lxml import etree

# Load XML and XSLT
xml_data = '''
<library>
    <book id="1">
        <title>XML Basics</title>
        <author>John Doe</author>
        <price>19.99</price>
    </book>
    <book id="2">
        <title>Advanced XML</title>
        <author>Jane Smith</author>
        <price>29.99</price>
    </book>
</library>
'''
xslt_data = '''
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
                <h1>Library Books</h1>
                <table border="1">
                    <tr>
                        <th>Title</th>
                        <th>Author</th>
                        <th>Price</th>
                    </tr>
                    <xsl:for-each select="library/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>
'''

# Parse XML and XSLT
xml_tree = etree.XML(xml_data)
xslt_tree = etree.XML(xslt_data)
transform = etree.XSLT(xslt_tree)

# Apply transformation
result = transform(xml_tree)
print(str(result))

Using Java

Java’s javax.xml.transform package supports XSLT transformations.

import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import java.io.StringReader;
import java.io.StringWriter;

public class XSLTExample {
    public static void main(String[] args) throws Exception {
        String xmlData = """
        <library>
            <book id="1">
                <title>XML Basics</title>
                <author>John Doe</author>
                <price>19.99</price>
            </book>
            <book id="2">
                <title>Advanced XML</title>
                <author>Jane Smith</author>
                <price>29.99</price>
            </book>
        </library>
        """;

        String xsltData = """
        <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
            <xsl:template match="/">
                <html>
                    <body>
                        <h1>Library Books</h1>
                        <table border="1">
                            <tr>
                                <th>Title</th>
                                <th>Author</th>
                                <th>Price</th>
                            </tr>
                            <xsl:for-each select="library/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>
        """;

        // Create sources
        Source xmlSource = new StreamSource(new StringReader(xmlData));
        Source xsltSource = new StreamSource(new StringReader(xsltData));

        // Create transformer
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(xsltSource);

        // Perform transformation
        StringWriter writer = new StringWriter();
        transformer.transform(xmlSource, new StreamResult(writer));

        System.out.println(writer.toString());
    }
}

XSLT Elements

Here are some commonly used XSLT elements:

ElementDescription
<xsl:template>Defines a transformation rule for matching nodes.
<xsl:value-of>Extracts the value of an XML element or attribute.
<xsl:for-each>Iterates over a set of nodes.
<xsl:if>Conditional transformation based on a condition.
<xsl:choose> / <xsl:when> / <xsl:otherwise>Conditional branching (similar to if-else).
<xsl:apply-templates>Applies templates to child nodes.

Benefits of XML and XSLT

  1. Dynamic Presentation: Transform XML data into HTML for web display.
  2. Data Transformation: Convert XML into other formats, such as JSON, CSV, or plain text.
  3. Cross-Browser Support: XSLT works natively in most web browsers.
  4. Reusable Rules: Write XSLT stylesheets once and apply them to multiple XML files.

Learn More at The Coding College

Looking to expand your knowledge? Dive deeper into XML, XSLT, and other powerful web technologies at The Coding College. We offer beginner-friendly tutorials and advanced guides to boost your programming skills.

Conclusion

XML and XSLT together are a powerful duo for transforming raw XML data into any desired format. Whether you’re working on web development, data migration, or API integrations, mastering XSLT can save you time and effort.

Leave a Comment