Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

XSLT Version 1 replace single/double quotes

I am trying to convert replace single/double quotes with " and ' respectively in xml

I am very new to xsl so very much appreciate if someone can help

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

For a dynamic method of replacing it will be better to create separate template with parameters as input text, what to replace and replace with.

So, in example input text is:

Your text "contains" some "strange" characters and parts.

In below XSL example, you can see replacing of " (") with " and ' ("'):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text"/>
    <!--template to replace-->
    <xsl:template name="template-replace">
        <xsl:param name="param.str"/>
        <xsl:param name="param.to.replace"/>
        <xsl:param name="param.replace.with"/>
        <xsl:choose>
            <xsl:when test="contains($param.str,$param.to.replace)">
                <xsl:value-of select="substring-before($param.str, $param.to.replace)"/>
                <xsl:value-of select="$param.replace.with"/>
                <xsl:call-template name="template-replace">
                    <xsl:with-param name="param.str" select="substring-after($param.str, $param.to.replace)"/>
                    <xsl:with-param name="param.to.replace" select="$param.to.replace"/>
                    <xsl:with-param name="param.replace.with" select="$param.replace.with"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$param.str"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <xsl:template match="/">
        <xsl:call-template name="template-replace">
            <!--put your text with quotes-->
            <xsl:with-param name="param.str">Your text "contains" some "strange" characters and parts.</xsl:with-param>
            <!--put quote to replace-->
            <xsl:with-param name="param.to.replace">"</xsl:with-param>
            <!--put quot and apos to replace with-->
            <xsl:with-param name="param.replace.with">"'</xsl:with-param>
        </xsl:call-template>
    </xsl:template>   
</xsl:stylesheet>

Then result of replacing will be as below:

Your text "'contains"' some "'strange"' characters and parts.

Hope it will help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...