【问题标题】:How to replace string with an element using XSLT如何使用 XSLT 将字符串替换为元素
【发布时间】:2011-10-11 14:35:43
【问题描述】:

如何使用 XSLT 1.0 将字符串替换为 XML 元素?

来源:

<body>This has a keyword and may have another keyword</body>

期望的输出:

<body>This has a <kw>keyword</kw> and may have another <kw>keyword</kw></body>

我有以下模板,但它只支持用文本替换字符串。

<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>

任何提示都会有所帮助。

谢谢。

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    从您已有的内容来看,似乎缺少的只是 如果元素名称是动态的,请使用 其中 XP 是 XPath 表达式。

    【讨论】:

    • 如何在同一文本中进行多次替换?如果我将结果存储在变量中,它们似乎会丢失。
    • 这个问题有点含糊。请提供您的 XML 和 XSLT 以及所需的输出。
    猜你喜欢
    • 2021-07-19
    • 2011-03-02
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多