XSLT Version 1 replace single/double quotes

2019-09-22 21:52发布

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

标签: xslt
1条回答
迷人小祖宗
2楼-- · 2019-09-22 22:20

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.

查看更多
登录 后发表回答