Outputting entity references in XSLT 2

Every now and then one has to output entitiy references unchanged from the source XSLT stylesheet to the result document, for example output ' ' to the XHTML source instead of just an actual space.

By default, an entitiy reference in the XSLT stylesheet will be "translated" into the actual character it represents when the stylesheet is transformed. Actually, it shouldn't make any difference whether ' ' or an actual space is outputted. It shouldn't, but it does due to differences in browsers and other applications. So if you have to force your entity references to be passed on unchanged to your result document, the way to go about it is by using character maps.

The usual way of using entity references:

<!DOCTYPE xsl:stylesheet [
    <!ENTITY nbsp "&#160;">
    <!ENTITY copy "&#169;">
]>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" method="xhtml" omit-xml-declaration="yes"/>
    <xsl:template match="/">
        <xsl:text>Space: &nbsp;</xsl:text>
        <br/>
        <xsl:text>Copyright: &copy;</xsl:text>
    </xsl:template>
</xsl:stylesheet>

This stylesheet will output the '&nbsp;' and '&copy;' entities as an actual space and '©'

To output entities unchanged, use character maps:

<!DOCTYPE xsl:stylesheet [
    <!ENTITY nbsp "&#160;">
    <!ENTITY copy "&#169;">
]>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" method="xhtml" omit-xml-declaration="yes" use-character-maps="char"/>
    <xsl:character-map name="char">
        <xsl:output-character character="&#160;" string="&amp;nbsp;"/>
        <xsl:output-character character="&#169;" string="&amp;copy;"/>
    </xsl:character-map>
    <xsl:template match="/">
        <xsl:text>Space: &nbsp;</xsl:text>
        <br/>
        <xsl:text>Copyright: &copy;</xsl:text>
    </xsl:template>
</xsl:stylesheet>

This stylesheet will output the '&nbsp;' and '&copy;' entities as '&nbsp;' and '&copy;' in the result XHTML document

It's obviously possible to skip the entity "declaration" and use entity numbers instead of names, like this:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" method="xhtml" omit-xml-declaration="yes" use-character-maps="char"/>
    <xsl:character-map name="char">
        <xsl:output-character character="&#160;" string="&amp;nbsp;"/>
        <xsl:output-character character="&#169;" string="&amp;copy;"/>
    </xsl:character-map>
    <xsl:template match="/">
        <xsl:text>Space: &#160;</xsl:text>
        <br/>
        <xsl:text>Copyright: &#169;</xsl:text>
    </xsl:template>
</xsl:stylesheet>

Comments

If you want to comment on this article you need to be logged in.

Published in 2011

2010

2009

2008

2007