Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

xslt - XSL: replace single and double quotes with ' and "

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[3] html - How to create even cell spacing within a

2.1m questions

2.1m answers

60 comments

57.0k users

...