Search code examples
xsltescapingapostrophe

HOW TO force XSLT to encode apostrophes as it does for quotes


in input XML I have a tag

<name>Sample " '</name>

in XSL I transform this tag with:

<xsl:variable name="productName" select="substring($elemXPath/name,1,50)"/>
<someTag someAttr="{$productName}"/>

When I run XSLT the output is:

<someTag someAttr="Sample &quot; '"/>

but I'd like to get

<someTag someAttr="Sample &quot; &apos;"/>

instead. I don't want to wrap every use of input data with separate escaping template because there is a waste number of such a places in my xslt.

I tried to encode apostrophes in the input file but when I put

<name>Sample &apos;</name>

to the input file then I got

<someTag someAttr="Sample &amp;apos;"/>

instead of

<someTag someAttr="Sample &apos;"/>

My question is how to force/configure XSLT to encode apostrophes as it does for quotes?


Solution

  • There isn't a way to control serialization to this level in XSLT 1.0.

    In XSLT 2.0 use <xsl:character-map> as in the following example:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                     version="2.0">
     <xsl:output method="xml" use-character-maps="myChars" omit-xml-declaration="yes"/>
    
     <xsl:character-map name="myChars">
      <xsl:output-character character="&quot;" string="&amp;quot;"/>
      <xsl:output-character character="&apos;" string="&amp;apos;"/>
     </xsl:character-map>
    
     <xsl:template match="/">
         <someTag someAttr="Sample &quot; &apos;"   />
     </xsl:template>
    </xsl:stylesheet>
    

    This produces the wanted result:

    <someTag someAttr="Sample &quot; &apos;"/>