Previous Page Next Page

Recipe 6.10. Handling String Literals Containing Quote Characters

Problem

String literals containing quote characters are difficult to deal with in XSLT 1.0 because there is no escape character.

Solution

This problem is alleviated by an enhancement that allows a quote character to be escaped by repeating the character. Here we are trying to match either double quote delimited strings or single quote delimited strings. We use single quotes for the test attribute so we must use double quotes for the string literal regex. This forces us to escape all literal double quotes by repeating them in the regex. The rules of XML force us to use the entity ' instead of ', but that is simply to emphasize that XML escaping is a separate issue that by itself does not provide a solution. In other words, if you replaced " " by ", you would make the XML parser happy, but the XSLT parser would still choke:

<xsl:if test=' matches(., " "" [^""] "" | &apos;[^&apos;] &apos;  ","x") '>
</xsl:if>

An equivalent solution is as follows:

<xsl:if test=" matches(., ' &quot; [^&quot;] &quot; | ''[^''] ''  ','x') ">
</xsl:if>

Discussion

The lack of an escape character in XSLT 1.0 was frustrating but one could always work around it by using variables and concatenation:

 <xsl:variable name="d-quote" select='"'/>
 <xsl:variable name="s-quote" select="'"/>
 <xsl:value-of select="concat('He said,', $d-quote, 'John', $s-quote, 's', 
 'dog turned green.', $d-quote)"/>


Previous Page Next Page