我想通过使用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>
答案 0 :(得分: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>