Davio
Davio

Reputation: 4737

Escaping & and CDATA with XSLT

Given the following XML:

<element><![CDATA[<p>Look at this beautiful house: &amp;#8962;</p>]]></element>

This XSL-T:

<xsl:template match='/element'>
    <xsl:value-of select="." disable-output-escaping="yes" />
</xsl:template>

Converts it into:

<p>Look at this beautiful house: &amp;#8962;</p>

So the CDATA is stripped okay, but how do I convert the &amp;#8962; into its proper representation: ⌂ ?

Upvotes: 2

Views: 3764

Answers (2)

Perry
Perry

Reputation: 611

For anybody who happens to stumble into this like I did, here is how I solved this dilemma in my ASP.Net MVC website for a XSLT 1.0 stylesheet. Worked fine for what I was needing. Hopefully it helps you.

First, I wrote this function and included it in my stylesheet:

<msxsl:script language="C#" implements-prefix="functions">
    <msxsl:assembly name="System.Web"/>
    <msxsl:using namespace="System.Web"/>
    <![CDATA[       
          public string RemoveAmpersandEncoding(string sText)
          {
            return sText.Replace("&amp;", "&");
          }
    ]]>
</msxsl:script>

Then I just called that function later in my stylesheet to get the necessary result:

<xsl:value-of select="functions:RemoveAmpersandEncoding(/ReservationsViewData/Campground/CancellationPolicy)" disable-output-escaping="yes"/>

Upvotes: 0

Davio
Davio

Reputation: 4737

I ended up fixing it with:

<xsl:value-of select="replace(current(), '&amp;amp;', '&amp;')" disable-output-escaping="yes"/>

I had to escape the ampersand here because I'm using it directly in XML, so the processor translates it back to replace(current(), '&amp;', '&') which is what I wanted.

I'm using XSLT v2 for this since it has the replace function.

Unfortunately, fixing the broken input at the source wasn't possible, a common problem in our field of work. :)

Upvotes: 1

Related Questions