2011-10-11 130 views
1

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

来源:

<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

从你已经有了,它看起来像所有缺少的是<的xsl:元素名称=“关键词”/>如果该元素的名称是动态的,使用<的xsl:元素名=“{XP}”/>其中XP是XPath表达式。

+0

如何在同一文本中做多个替换?如果我将结果存储在变量中,他们似乎会迷失方向。 – joe

+0

这个问题有点含糊。请提供您的XML和XSLT以及所需的输出。 – Dabbler