Categories
technology

Escaping entities using XSLT

While writing the last post I didn’t fancy the idea of hand escaping the HTML entities into the MSN XML output. So I cheated using a funky little piece of XSLT that I cooked up earlier tonight. It’s listed below…

<xsl:stylesheet version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="no" doctype-
system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" doctype-public=
"-//W3C//DTD XHTML 1.0 Transitional//EN"> </xsl:output>
<xsl:template match="/">
<xsl:call-template name="escapexml">
<xsl:with-param name="block" select="."> </xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template name="escapexml">
<xsl:param name="block"> </xsl:param>
<xsl:for-each select="$block/*|$block/text()">
<xsl:choose>
<xsl:when test="self::text()">
<xsl:value-of select="."> </xsl:value-of>
</xsl:when>
<xsl:otherwise>
<xsl:text> &lt;</xsl:text>
<xsl:value-of select="name(.)"> </xsl:value-of>
<xsl:for-each select="@*">
<xsl:value-of select="concat(' ', name())">
</xsl:value-of>
<xsl:text> ="</xsl:text>
<xsl:value-of select="."> </xsl:value-of>
<xsl:text> "</xsl:text>
</xsl:for-each>
<xsl:text> &gt; </xsl:text>
<xsl:choose>
<xsl:when test="*">
<xsl:call-template name="escapexml">
<xsl:with-param name="block" select=".">
; </xsl:with-param>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."> </xsl:value-of>
</xsl:otherwise>
</xsl:choose>
<xsl:text> &lt;/</xsl:text>
<xsl:value-of select="name(.)"> </xsl:value-of>
<xsl:text> &gt; </xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

I’ll produce a tidier more beautifying version when I get the time but it’s OK for a first attempt and I know of at least one person who’s asked me to do something similiar in the past. And on that note.. it could be time to hit the hay 😉

Leave a Reply

Your email address will not be published. Required fields are marked *