Search code examples
xslttranslate

How can I translate ' into an apostrophe in xslt


The relevant parts of the code:

<xsl:variable name="apos">'</xsl:variable>
<xsl:variable name="and" select='"&#039;"' />

<xsl:value-of select="translate(products_name/node(),$and,$apos)"/>

I'm thinking this should be a simple thing and that the above code should work but it doesn't effect the output at all.

(I used variables because names cannot begin within an ampersand and using just an apostrophe brings up a compile error.)

I've tested the code to make sure the translate is working using strings and there are no errors there.

Any help would be greatly appreciated.


Solution

  • You are on the right track, but not yet there: Your problem is, that XSL is a language that itself is written using XML. For all XML languages, the parser automatically decodes XML entities. The XSLT engine only comes afterwards.

    As a result, the XSLT engine neither does nor can distinguish whether you wrote ' or &#039; - it's the same. For your problem, this has two effects:

    1. You have to use a variable containing the apostrope - this is because the apostrophe itself is reserved for string literals in expressions that may contain functions. Even for <xsl:value-of select="translate(products_name/node(),$and,'&#039;')"/>, the XML parser transforms the entity into an apostrophe, i.e. <xsl:value-of select="translate(products_name/node(),$and,''')"/>

    2. You have to escape the ampersand used in the string you search for: for the XSL engine, the variable "and" contains the value ', i.e. you are replacing an apostrophe with an apostrophe.

    Working solution:

    <xsl:variable name="apos">'</xsl:variable>
    <xsl:value-of select='translate(text(), "&amp;#039;", $apos)'/>