[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

Re: [xsl] Ampersand in CDATA


Subject: Re: [xsl] Ampersand in CDATA
From: Abel Braaksma <abel.online@xxxxxxxxx>
Date: Sat, 01 Sep 2007 01:54:16 +0200

Geoffrey Lee wrote:
Hi, I have the following XSL template using the PHP5 XSLT 1.0 processor:

<xsl:template match="/">
<![CDATA[ & ]]>
</xsl:template>

This is the PHP code I use to execute the transformation:

  // Load XSL file
  $xsl_dom = new DOMDocument();
  $xsl_dom->load($xsl_filename);

  // Apply XSL
  $xsl = new XSLTProcessor();
  $xsl->importStyleSheet($xsl_dom);
  echo $xsl->transformToXML($xml_dom);

I expect it to output just an ampersand by itself, but instead, I'm
getting "&amp;". What's going on?

Why would you expect only an ampersand? You are probably outputting XML and in XML, an ampersand on its own (unless in CDATA, a PI or a comment) is not valid. Not sure what you are after, but the CDATA only tells the XML processor (the one that processes the XSLT prior the actual XSLT processor) that the texts inside these tags are not to be interpreted as XML data.


This means, in XML terms, that the following are equivalent (almost equal, but there are small differences, but that should be asked on some XML list):

<xsl:template match="/">&#x26;</xsl:template>
<xsl:template match="/">&#38;</xsl:template>
<xsl:template match="/">&amp;</xsl:template>
<xsl:template match="/"><![CDATA[&]]></xsl:template>

After processing/interpreting the XML, the XSLT processor takes over and starts to apply the templates. After some phases of processing, it will start the outputting, which is different depending on the method you have chosen. In this case (you didn't show) I assume it is either html, xhtml or xml. The XSLT processor is REQUIRED to make the output valid (and there are only very limited ways to make the output invalid or unwell-formed XML).

If you want a literal ampersand, you should either output it as part of a comment, or you should use a character-map (only in XSLT 2.0, and you use XSLT 1.0), or if illegal XML is not your concern but you just want text, you can output as text. To do this, change your code as follows:

<xsl:output method="text" />
<xsl:template match="/">&amp;</xsl:template>

Again, it doesn't matter a bit in what way you express your ampersand, as long as you make sure that the input XSLT (which is XML first of) is valid.

Hope this helps,

Cheers,
-- Abel Braaksma


Current Thread
Keywords