【发布时间】:2015-03-04 12:35:09
【问题描述】:
我有一个 XML 文档,我正在尝试转换并在某些值出现在文本节点或名为 message 的属性中时对某些值进行字符串替换。我的 xsl 文件在下面,但主要问题是当替换发生在 message 属性中时,它实际上替换了整个属性而不仅仅是该属性的值,所以
<mynode message="hello, replaceThisText"></mynode>
变成
<mynode>hello, withThisValue</mynode>
代替
<mynode message="hello, withThisValue"></mynode>
当文本出现在像这样的文本节点中时
<mynode>hello, replaceThisText</mynode>
然后它按预期工作。
我还没有完成大量的 XSLT 工作,所以我有点卡在这里。任何帮助,将不胜感激。谢谢。
<xsl:template match="text()|@message">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text"><xsl:value-of select="."/></xsl:with-param>
<xsl:with-param name="replace" select="'replaceThisText'"/>
<xsl:with-param name="by" select="'withThisValue'"/>
</xsl:call-template>
</xsl:template>
<!-- string-replace-all from http://geekswithblogs.net/Erik/archive/2008/04/01/120915.aspx -->
<xsl:template name="string-replace-all">
<xsl:param name="text" />
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text,$replace)" />
<xsl:value-of select="$by" />
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text"
select="substring-after($text,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
【问题讨论】: