XSLT字符串替换,多个字符串
问题描述:
我想用xslt 1.0实现查找和替换字符串。 问题是,我不得不更换不同值的多个字符串。例如,我输入的XML是如下XSLT字符串替换,多个字符串
<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输入的字符串应该被伦敦和英格兰取代。 我发现了很多例子来查找和替换单个字符串,但我不知道如何替换具有不同值的多个字符串。 任何建议吗?
在此先感谢
答
这将是容易得多,如果你可以使用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>
+0
非常感谢你 –
在这里看到一个可能的方法:http://stackoverflow.com/questions/33527077/change-html-dynamically-thru-xsl/33529970#33529970 –