-1

I have a XSL which I am using to transform one XML to another like:

<xsl:value-of select="somestatement"/>

where some statement has single quotes and double quotes. Ex: This is an "example" string. I have 'single quotes'

I want to replace single quotes with &apos; and double quotes with &quot; so that output string will be :

This is an &quot;example&quot; string. I have &apos;single quotes&apos;

Can someone please suggest a solution for this?

Thanks for the help in advance.

matthias_h
  • 11,356
  • 9
  • 22
  • 40
javabee
  • 1
  • 1
  • 1
  • 1
    I don't understand the question. Single quote(`'`) is represented in XML as `'` and a double quote(`"`) as `"`. There is no need for any replacement. – Lingamurthy CS Dec 24 '14 at 04:35
  • possible duplicate of [want to replace " with " from a xml](http://stackoverflow.com/questions/14217025/want-to-replace-with-quot-from-a-xml) – matthias_h Dec 24 '14 at 04:43
  • @LingamurthyCS: Due to some agreement with a vendor we have to ship XML with ' and " instead of ' and " – javabee Dec 24 '14 at 18:41

1 Answers1

2

You need to call a named recursive template for this. Try:

<xsl:template name="escape-quotes">
    <xsl:param name="text"/>
    <xsl:param name="searchString">'</xsl:param>
    <xsl:param name="replaceString">&amp;apos;</xsl:param>
    <xsl:variable name="apos">'</xsl:variable>  
    <xsl:choose>
        <xsl:when test="contains($text,$searchString)">
            <xsl:call-template name="escape-quotes">
                <xsl:with-param name="text" select="concat(substring-before($text,$searchString), $replaceString, substring-after($text,$searchString))"/>
                <xsl:with-param name="searchString" select="$searchString"/>
                <xsl:with-param name="replaceString" select="$replaceString"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:when test="$searchString=$apos">
            <xsl:call-template name="escape-quotes">
                <xsl:with-param name="text" select="$text"/>
                <xsl:with-param name="searchString">"</xsl:with-param>
                <xsl:with-param name="replaceString">&amp;quot;</xsl:with-param>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text" disable-output-escaping="yes"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Example of calling the template:

<output>
    <xsl:call-template name="escape-quotes">
        <xsl:with-param name="text">This is an "example" string. I have 'single quotes'.</xsl:with-param>
    </xsl:call-template>
</output>

Result:

<output>This is an &quot;example&quot; string. I have &apos;single quotes&apos;.</output>
michael.hor257k
  • 113,275
  • 6
  • 33
  • 51