我有一个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>
答案 0 :(得分:2)
您的模板与属性匹配,但它不会输出一个属性。
请注意,属性的值不是节点。因此,您必须为文本节点和属性使用单独的模板:
<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>