XSLT字符串替换,多个字符串

时间:2016-05-15 22:23:36

标签: xslt

我想使用xslt 1.0实现查找和替换字符串。 问题是,我必须用不同的值替换多个字符串。例如,我的输入xml如下所示

<process xmlns:client="http://xmlns.oracle.com/ErrorHandler" xmlns="http://xmlns.oracle.com/ErrorHandler">
    <client:result>The city name is $key1$ and Country name is $key2$   </client:result>
</process>

结果应该是

<process xmlns:client="http://xmlns.oracle.com/ErrorHandler" xmlns="http://xmlns.oracle.com/ErrorHandler">
    <client:result>The city name is London and Country name is England  </client:result>
</process>
输入字符串中的 $ key1 $和$ key2 $应替换为伦敦和英格兰。 我找到了很多例子来查找和替换单个字符串,但我不知道如何用不同的值替换多个字符串。 有什么建议吗?

提前致谢

1 个答案:

答案 0 :(得分:2)

如果您可以使用XSLT 2.0或更高版本,那将会容易得多。它可以很简单:

replace(replace(., '\$key1\$', 'London'), '\$key2\$', 'England')

但是,如果您遇到XSLT 1.0,可以use a recursive template to perform the replace,并为要替换的每个令牌调用它(使用先前调用的产品作为下一个调用的输入):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:client="http://xmlns.oracle.com/ErrorHandler"
    version="1.0">

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

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="client:result">
        <xsl:variable name="orig" select="string(.)"/>
        <xsl:variable name="key1">
            <xsl:call-template name="replace-string">
                <xsl:with-param name="text" select="$orig"/>
                <xsl:with-param name="replace" select="'$key1$'"/>
                <xsl:with-param name="with" select="'London'"/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:variable name="key2">
            <xsl:call-template name="replace-string">
                <xsl:with-param name="text" select="$key1"/>
                <xsl:with-param name="replace" select="'$key2$'"/>
                <xsl:with-param name="with" select="'England'"/>
            </xsl:call-template>
        </xsl:variable>

        <xsl:copy>
            <xsl:value-of select="$key2"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>