Thursday, 29 November 2007

 

XSLT: output an XML escaped copy of the source tree fragment

I've assembled the following hack after gathering some ideas from the net. It allows to have a copy of the source tree in the output, but unlike <xsl:copy>, it outputs the copy as text with XML escaping. Limitation is that it only supports elements, text nodes and attributes. But this can easily be extended if need arises.

<!-- the hack below outputs escaped copy of the current node set -->
<xsl:template match="*|@*" mode="verb">
<xsl:variable name="node-type">
<xsl:call-template name="node-type"/>
</xsl:variable>
<xsl:choose>
<xsl:when test="$node-type='element'"> <!-- element -->
<xsl:text>&lt;</xsl:text>
<xsl:value-of select="name()"/>
<xsl:apply-templates select="@*" mode="verb"/>
<xsl:text>&gt;</xsl:text>
<xsl:apply-templates mode="verb"/>
<xsl:text>&lt;/</xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>&gt;</xsl:text>
</xsl:when>
<xsl:when test="$node-type='text'"> <!-- text -->
<xsl:value-of select="self::text()"/>
</xsl:when>
<xsl:when test="$node-type='attribute'"> <!--any attribute-->
<xsl:text> </xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>="</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</xsl:text>
</xsl:when>
</xsl:choose>
</xsl:template>

<xsl:template name="node-type">
<xsl:param name="node" select="."/>
<xsl:apply-templates mode="nodetype" select="$node"/>
</xsl:template>
<xsl:template mode="nodetype" match="*">element</xsl:template>
<xsl:template mode="nodetype" match="@*">attribute</xsl:template>
<xsl:template mode="nodetype" match="text()">text</xsl:template>

Labels:


Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom], Comments [Atom]