Search code examples
ampersand

XSLT crashes when encountering Ampersand sign


I am currently running in some trouble when trying to output a certain XML tag containing the Ampersand sign (&).

So more concrete, when I try to output the following tag. I get an error

<fullname>Ben & Jerry</fullname>

Using the following tag however runs just fine

<fullname>Ben and Jerry</fullname>

I have tried it with the following code

<xsl:template match="fullname">
    <xsl:apply-templates/>
</xsl:template>

And I also tried

<xsl:template match="fullname">
    <xsl:value-of-select="." disable-output-escaping="Yes"/>
</xsl:template>

Both resulted in an error. The only way how I get it to work is by using CDATA like this

<fullname><![CDATA[Ben & Jerry]]></fullname>

However, I have no control over the XML files I receive, and as such this is not a viable option. Is there something I can do within the XSLT to circumvent/fix this problem?

Thanks!


Solution

  • Ampersand can't appear as itself in well-formed XML. Your example should be

    <fullname>Ben &amp; Jerry</fullname>
    

    I don't think you'll be able to get around this with any XSLT processor. You need to fix whatever generates the XML so it is well-formed.