我有一个 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>
最佳答案
您的模板与某个属性匹配,但不输出。
请注意,属性的值不是节点。因此,您必须为文本节点和属性使用单独的模板:
<xsl:template match="text()">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="."/>
<xsl:with-param name="replace" select="'replaceThisText'"/>
<xsl:with-param name="by" select="'withThisValue'"/>
</xsl:call-template>
</xsl:template>
<xsl:template match="@message">
<xsl:attribute name="message">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="."/>
<xsl:with-param name="replace" select="'replaceThisText'"/>
<xsl:with-param name="by" select="'withThisValue'"/>
</xsl:call-template>
</xsl:attribute>
</xsl:template>
关于xml - XSLT 替换属性值和文本节点中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27805510/