使用xslt替换函数将单词替换为元素

时间:2010-12-10 11:34:47

标签: xslt xslt-2.0

我想用XSLT替换函数来替换文本中的单词

<strong>word</strong>.

我写了以下模板:

<xsl:template name="make-bold">
  <xsl:param name="text"/>
  <xsl:param name="word"/>
  <xsl:variable name="replacement">
     <strong><xsl:value-of select="$word"/></strong>
  </xsl:variable>
  <xsl:value-of select="replace($text, $word,  $replacement )" />
</xsl:template>

不幸的是,不会呈现,其余的工作也是如此。

有人可以帮助我吗?

Best,Suidu

2 个答案:

答案 0 :(得分:3)

替换函数http://www.w3.org/TR/xpath-functions/#func-replace接受一个字符串并返回一个字符串。您似乎想要创建一个元素节点,而不是一个简单的字符串。在这种情况下,使用analyze-string http://www.w3.org/TR/xslt20/#analyze-string而不是替换可能有所帮助。

以下是一个示例XSLT 2.0样式表:

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="xs"
  version="2.0">

  <xsl:output method="html" indent="no"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@*, node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="p">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:apply-templates select="text()" mode="wrap">
        <xsl:with-param name="words" as="xs:string+" select="('foo', 'bar')"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="text()" mode="wrap">
    <xsl:param name="words" as="xs:string+"/>
    <xsl:param name="wrapper-name" as="xs:string" select="'strong'"/>
    <xsl:analyze-string select="." regex="{string-join($words, '|')}">
      <xsl:matching-substring>
        <xsl:element name="{$wrapper-name}">
          <xsl:value-of select="."/>
        </xsl:element>
      </xsl:matching-substring>
      <xsl:non-matching-substring>
        <xsl:value-of select="."/>
      </xsl:non-matching-substring>
    </xsl:analyze-string>
  </xsl:template>

</xsl:stylesheet>

使用XSLT 2.0处理器(如Saxon 9)对照以下输入示例运行

<html>
  <body>
    <p>This is an example with foo and bar words.</p>
  </body>
</html>

输出如下:

<html>
  <body>
    <p>This is an example with <strong>foo</strong> and <strong>bar</strong> words.</p>
  </body>
</html>

答案 1 :(得分:0)

hmm是因为这里它被替换的字符串值,你可能会尝试使用节点集吗?

我无法测试,因为我不使用xslt 2.0,但你可能会尝试一个递归模板,即

<xsl:template match="yourtextelement">
   <xsl:call-template name="MaketextStrong">
</xsl:template>

<xsl:template name="MaketextStrong">
   <xsl:param name="text" select="."/>
   <xsl:choose>
   <xsl:when test="contains($text, 'texttomakestrong')">
      <xsl:value-of select="substring-before($text, 'texttomakestrong')"/>
      <strong>texttomakestrong</strong>
      <xsl:call-template name="break">
          <xsl:with-param name="text" select="substring-after($text,
'texttomakestrong')"/>
      </xsl:call-template>
   </xsl:when>
   <xsl:otherwise>
 <xsl:value-of select="$text"/>
   </xsl:otherwise>
   </xsl:choose>
</xsl:template>
相关问题