1

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?

Kragh
  • 403
  • 4
  • 11

2 Answers2

2

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;"/>
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
  • [This related post](http://stackoverflow.com/a/1103319/1594157) has a solution for XSLT 1.0 which does the job. – sufw Apr 28 '14 at 04:58
  • @sufw, `&apos` is certainly different than `'` when both strings are treatd as parsed character content. The first string has length of 5, while the second has length of 1. – Dimitre Novatchev Apr 28 '14 at 05:20
1

In general, you shouldn't care which of two equivalent serialisations of your data the XSLT processor chooses. Any sane consumer of the data will treat them the same way; if it doesn't you should fix the consumer.

However, for pragmatic reasons XSLT 1.0 provides disable-output-escaping and XSLT 2.0 provides character maps so you can tweak the output at this level if you really must.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164