4

How do you replace an xml value, for example:

<name>Linda O'Connel</name>

to:

<name>Linda O''Connel</name>

via XSLT?

I need this because I have to pass this value in a powershell command line and to other platforms since the "double single quote" is needed to escape the apostrophe/single quotes.

EdgyIT
  • 171
  • 2
  • 9
  • 2
    You do realize that PowerShell could just read the XML content and you could work with it that way right? Rather than trying to convert it to a string, and then escape the string. – TheMadTechnician May 20 '15 at 02:14
  • I definitely can do that, But i need to pass "double single quote" to other platforms as well as this is how they escape the single quotes. So yea if there's any way this can be done via XSLT? Thanks – EdgyIT May 20 '15 at 02:28

2 Answers2

9

Assuming an XSLT 1.0 processor, you will need to use a recursive named template for this, e.g:

<xsl:template name="replace">
    <xsl:param name="text"/>
    <xsl:param name="searchString">'</xsl:param>
    <xsl:param name="replaceString">''</xsl:param>
    <xsl:choose>
        <xsl:when test="contains($text,$searchString)">
            <xsl:value-of select="substring-before($text,$searchString)"/>
            <xsl:value-of select="$replaceString"/>
           <!--  recursive call -->
            <xsl:call-template name="replace">
                <xsl:with-param name="text" select="substring-after($text,$searchString)"/>
                <xsl:with-param name="searchString" select="$searchString"/>
                <xsl:with-param name="replaceString" select="$replaceString"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Example of call:

<xsl:template match="name">
    <xsl:copy>
        <xsl:call-template name="replace">
            <xsl:with-param name="text" select="."/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>
michael.hor257k
  • 113,275
  • 6
  • 33
  • 51
-1

You can also try out the following.

  <xsl:variable name="temp">'</xsl:variable>
  <name>
    <xsl:value-of select="concat(substring-before(name,$temp),$temp,$temp,substring-after(name,$temp))"/>
  </name>
Saurav
  • 592
  • 4
  • 21