Welcome to CodeYourCraft's XSLT Preserve-Space tutorial! In this lesson, we'll explore the XSL Transformations (XSLT) technique used to preserve whitespace in XML documents. Let's dive in!
XSLT, or Extensible Stylesheet Language Transformations, is a language that allows you to transform XML documents into other formats such as HTML, JSON, and plain text. XSLT helps you manipulate and format XML data for display in a user-friendly manner.
White space (spaces, tabs, and line breaks) plays a crucial role in XML documents, especially when they are intended for human readability. Unfortunately, XSLT's default behavior is to remove all white space during the transformation process. To address this issue, XSLT provides the xsl:preserve-space instruction.
The xsl:preserve-space instruction is an XSLT element that ensures whitespace is maintained in the output. Here's how it works:
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<xsl:if test="normalize-space(.)">
<xsl:text> </xsl:text>
<xsl:value-of select="normalize-space(.)"/>
</xsl:if>
</xsl:copy>
</xsl:template>This template will copy all elements and attributes in the input XML document and include any white space between them.
Let's look at a simple XML document:
<book>
<title>The Catcher in the Rye</title>
<author>J.D. Salinger</author>
<year>1951</year>
<description>A novel about adolescence, disillusionment, and the loss of innocence.</description>
</book>Now, let's create an XSLT stylesheet to preserve white space when transforming this XML:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<xsl:if test="normalize-space(.)">
<xsl:text> </xsl:text>
<xsl:value-of select="normalize-space(.)"/>
</xsl:if>
</xsl:copy>
</xsl:template>
<xsl:template match="book">
<html>
<body>
<h1><xsl:value-of select="title"/></h1>
<p><xsl:value-of select="author"/></p>
<p><xsl:value-of select="year"/></p>
<p><xsl:value-of select="description"/></p>
</body>
</html>
</xsl:template>
</xsl:stylesheet>When you apply this XSLT stylesheet to the XML document, it will transform it into the following HTML:
<html>
<body>
<h1>The Catcher in the Rye</h1>
<p>J.D. Salinger</p>
<p>1951</p>
<p>A novel about adolescence, disillusionment, and the loss of innocence.</p>
</body>
</html>Notice how the white space in the original XML document is preserved in the resulting HTML.
What is the purpose of the `xsl:preserve-space` instruction in XSLT?
That's all for today! In the next lesson, we'll dive deeper into XSLT and explore more advanced techniques for transforming XML documents. Stay tuned! 🚀