如何使用XSLT将元素替换为元素

时间:2011-10-11 14:35:44

标签: xml xslt

如何使用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>

任何提示都会有所帮助。

感谢。

1 个答案:

答案 0 :(得分:1)

根据您已有的内容,看起来缺少的是&lt; xsl:element name =“keyword”/&gt;如果元素名称是动态的,请使用&lt; xsl:element name =“{XP}”/&gt;其中XP是XPath表达式。

相关问题