2

我想使用 XSLT 1.0 在 Text 中找到一些关键字

  • contentText :海洋天气预报、警告、概要和冰情。数百个陆地和浮标站观测和海洋天气预报、警告、概要和冰情。数百个陆地和浮标站观测。

  • 关键词:“海洋天气,海洋天气,海洋天气”

  • 分隔符 : ,

以下代码只是一个关键字作品......但我想找到多个关键字(“海洋天气,海洋天气,海洋天气”)

<xsl:choose>
  '<xsl:when test="contains($contentText,$keyWordLower)">
    <xsl:value-of select="substring-before($contentText,$keyWordLower)" disable-output-escaping="yes"/>
    <span class="texthighlight">
      <xsl:value-of select="$keyWordLower" disable-output-escaping="yes"/>
    </span>
    <!--Recursive call to create the string after keyword-->
    <xsl:call-template name="ReplaceSections">
      <xsl:with-param name="contentText" select="substring-after($contentText,$keyWordLower)"/>
      <xsl:with-param name="keyWordLower" select="$keyWordLower"/>
    </xsl:call-template>
  </xsl:when> <xsl:otherwise>
    <xsl:value-of select="$contentText"/>
  </xsl:otherwise>
</xsl:choose>
4

1 回答 1

3

这种转变

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:param name="pKeyWords">
  <kw>Marine weather</kw>
  <kw>marine weather</kw>
  <kw>Marine Weather</kw>
 </xsl:param>

 <xsl:variable name="vKeyWords" select=
 "document('')/*/xsl:param[@name='pKeyWords']/*"/>

 <xsl:template match="/*">
  <t><xsl:apply-templates/></t>
 </xsl:template>

 <xsl:template match="text()" name="highlightKWs">
  <xsl:param name="pText" select="."/>

  <xsl:if test="not($vKeyWords[contains($pText,.)])">
   <xsl:value-of select="$pText"/>
  </xsl:if>

  <xsl:apply-templates select="$vKeyWords[contains($pText,.)]">
   <xsl:sort select="string-length(substring-before($pText,.))"
    data-type="number"/>
   <xsl:with-param name="pText" select="$pText"/>
  </xsl:apply-templates>
 </xsl:template>

 <xsl:template match="kw">
   <xsl:param name="pText"/>
   <xsl:if test="position()=1">
    <xsl:value-of select="substring-before($pText, .)"/>
    <span class="texthighlight">
     <xsl:value-of select="."/>
    </span>
    <xsl:call-template name="highlightKWs">
     <xsl:with-param name="pText" select="substring-after($pText, .)"/>
    </xsl:call-template>
   </xsl:if>
 </xsl:template>
</xsl:stylesheet>

应用于以下 XML 文档时:

<t>Marine weather forecasts,
warnings, synopsis, and ice conditions.
Hundreds of land and buoy station observations
across and marine weather forecasts, warnings,
synopsis, and ice conditions. Hundreds of land
and buoy station observations across.</t>

产生想要的正确结果:

<t>
   <span class="texthighlight">Marine weather</span> forecasts,
warnings, synopsis, and ice conditions.
Hundreds of land and buoy station observations
across and <span class="texthighlight">marine weather</span> forecasts, warnings,
synopsis, and ice conditions. Hundreds of land
and buoy station observations across.</t>
于 2013-02-14T04:18:17.560 回答