XML technologies / XSLT / XSLT Kochbuch / Making use of XSLT 2.0 / Processing string literals containing quotation marks

(Excerpt from "XSLT Kochbuch" by Sal Mangano)

Problem

String literals containing quotation marks are difficult in XSLT 1.0 because it has no escape character.

Solution

An extension eases this problem by allowing a quotation mark to be escaped by doubling it. Here we match strings delimited by either double or single quotes. We use single quotes for the test attribute, so for the string literal regex we must use double quotes. Every literal double quote must therefore be escaped by doubling it in the regex. XML rules require us to use entity ' instead of ', but this merely emphasizes that XML escaping is a separate issue that does not solve the problem by itself. In other words, replacing " " with " " would satisfy the XML parser, but the XSLT parser would still fail:

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

An equivalent solution is:

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

Discussion

The lack of an escape character in XSLT 1.0 was frustrating, but variables and concatenation always offered a workaround:

<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)"/>

  

 

 

 

back to top