I am using XSLT to transform a XML into a html/php file. In this XSLT I replace some tags by php code and now I have to pass attribute values into that php code. My problem now is that I have to escape single quotes with a backslash to get it work. Is this possible with XSLT.
Example:
<xsl:template match="foo">
<xsl:processing-instruction name="php">$this->doSomething('<xsl:value-of select="./@bar" />');</xsl:processing-instruction>
</xsl:template>
If I now had a template:
<foo bar="test'xyz"/>
This would generate:
<?php $this->doSomething('test'xyz');?>
What I now want to achieve is the following:
<?php $this->doSomething('test\'xyz');?>
So I want to replace all single quotes by \'
Why don't you just use the standard XSLT 2.0 replace function? Or the XSLT 1.0 replace implementation xslt 1.0 string replace function
Just use:
Use a recursive template to do the find/replace:
Applied to your example:
Note:
<xsl:text>
to explicitly define text intended for the output, and not have to worry about whitespace between that text and template calls.'
for the single quote (a.k.a. apostrophe)For an XSLT 1.0 solution either write your own recursive solution, or you can use the FXSL template
str-map
:When applied on the provided XML document:
the wanted, correct result is produced:
Here's a simpler, inelegant, but quick method for replacing single quotes:
1) Define a variable that contains just an apostrophe. xsl:text is required to get xsl to treat ' as a simple character
2) Use replace function using that variable as the string to match. In this example, I'm simply removing it.