xml - XSLT 替换属性值和文本节点中的文本

标签 xml xslt replace xslt-1.0

我有一个 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/

相关文章:

JavaScript 正则表达式替换 - 但只是匹配字符串的一部分?

javascript - 脚本标签内的 HTML 实体未转换?

android - 如何在 Android 上使应用程序的背景模糊?就像我们在 iPhone 上调用 Siri 时的效果

javascript - 使用 xsl 的 XML 日期格式

java - java 中的 xmlns 和 xslt 转换

xslt - XMLStarlet + XInclude + XSLT

replace - 如何替换Julia中字符串中的多个字符

python - Pandas .str.replace 和不区分大小写

java - 用于基于表单的身份验证的 Tomcat 7 领域配置

android - 我可以删除 xml 中底层项目的背景颜色吗?