XSLT – munging apostrophes

Escaping escapes can be a near impossible task with XSLT.

Here is the standard form of testing whether a string matches


<xsl:if
test=”countryName=’USA’” >
Name matches
</xsl:if>

What happens if the country name is People’s Republic of China instead?

  1. You can’t use the apostrophe because the single quote is already used to delimit the string.
  2. You can’t use double quotes around the string because it is already used to delimit the attribute
  3. You can’t use the &apos; entity because it is converted to a single quote inside the attribute, so the attribute sees 'People's Republic of China' any way (which is an illegal expression).

Solution 1 – use string concatenation


<xsl:if
test=”countryName=concat(‘People,’, &quot;&apos;&quot;, ‘s Republic of China’)” >
Name matches
</xsl:if>

Solution 2 – use a variable


<xsl:variable name=”apos”>'</xsl:variable>
<xsl:if
test=”countryName=concat(‘People,’, $apos, ‘s Republic of China’)” >
Name matches
</xsl:if>

Solution 3 – thanks Jörn Horstmann


<xsl:variable name=”PRC”>People's Republic of China</xsl:variable>
<xsl:if
test=”countryName=$PRC” >
Name matches
</xsl:if>

About this entry