« More on MSH | Main | Digital Mixing »

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 ;-)

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

About

This page contains a single entry from the blog posted on November 16, 2004 2:09 AM.

The previous post in this blog was More on MSH.

The next post in this blog is Digital Mixing.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33