Generating Text with xsl:text
You can create text nodes with the <xsl:text> element, allowing you to do things such as replace whole elements with text on the fly. One reason you can use <xsl:text> is to preserve whitespace, as in this example from earlier in the chapter, where I used <xsl:text> to insert spaces:
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/PLANETS"> <HTML> <HEAD> <TITLE> The Planets Table </TITLE> </HEAD> <BODY> <H1> The Planets Table </H1> <TABLE> <TD>Name</TD> <TD>Mass</TD> <TD>Radius</TD> <TD>Day</TD> <xsl:apply-templates/> </TABLE> </BODY> </HTML> </xsl:template> <xsl:template match="PLANET"> <TR> <TD><xsl:value-of select="NAME"/></TD> <TD><xsl:apply-templates select="MASS"/></TD> <TD><xsl:apply-templates select="RADIUS"/></TD> </TR> </xsl:template> <xsl:template match="MASS"> <xsl:value-of select="."/> <xsl:text> </xsl:text> <xsl:value-of select="@UNITS"/> </xsl:template> <xsl:template match="RADIUS"> <xsl:value-of select="."/> <xsl:text> </xsl:text> <xsl:value-of select="@UNITS"/> </xsl:template> <xsl:template match="DAY"> <xsl:value-of select="."/> <xsl:text> </xsl:text> <xsl:value-of select="@UNITS"/> </xsl:template> </xsl:stylesheet>
Another reason to use <xsl:text> is when you want characters such as < and & to appear in your output document, not < and &. To do that, you set the <xsl:text> elements disable-output-escaping attribute to "yes":
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="PLANETS"> <HTML> <HEAD> <TITLE> Planets </TITLE> </HEAD> <BODY> <xsl:apply-templates select="PLANET"/> </BODY> </HTML> </xsl:template> <xsl:template match="PLANET"> <xsl:text disable-output-escaping = "yes"> <PLANET> </xsl:text> </xsl:template> </xsl:stylesheet>
Here is the result:
<HTML> <HEAD> <TITLE> Planets </TITLE> </HEAD> <BODY> <PLANET> <PLANET> <PLANET> </BODY> </HTML>