非常抱歉,问题的措辞不够清晰。我尝试解释一下我的意图。 基本上,我从搜索中得到了Xml格式的输出,在这个Xml中有一个节点如下:
<FIELD NAME="body">
Somebody named
<key>Doris</key>
and
<key>Arnie</key>
</FIELD>
简而言之,我需要的是将“<key>”替换为“<strong>”,即突出显示搜索命中项(关键节点值是用户搜索的内容)。在Xslt中,我不知道用户从哪里搜索,除了查询Xml -> FIELD[@name='body']/key。
现在我有一些疯狂的代码,将提取搜索词(“Doris”)前面的任何内容,但这仅适用于一个搜索词。我们需要它处理多个搜索词。我们使用的代码如下:
<xsl:template name="highlighter">
<xsl:param name="text"/>
<xsl:param name="what"/>
<xsl:choose>
<xsl:when test="contains($text, $what) and string-length($what) > 0">
<xsl:variable name="before" select="substring-before($text, $what)"/>
<xsl:variable name="after" select="substring-after($text, $what)"/>
<xsl:variable name="real-before" select="substring($text, 1, string-length($before))"/>
<xsl:variable name="real-what" select="substring($text, string-length($before) + 1, string-length($what))"/>
<xsl:variable name="real-after" select="substring($text, string-length($before) + string-length($what) + 1)"/>
<xsl:value-of select="$real-before"/>
<strong>
<xsl:value-of select="$real-what"/>
</strong>
<xsl:call-template name="highlighter">
<xsl:with-param name="text" select="$real-after"/>
<xsl:with-param name="what" select="$what"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
我一直在尝试使用不同的搜索词多次调用此代码,但我不知道如何将上一个调用到模板的输出作为下一个调用的输入。在代码中,它应该是这样的:
string body = doc.SelectSingleNode("FIELD[@NAME='body']");
NodeCollection nodes = doc.SelectNodes("FIELD[@NAME='body']/key");
foreach (var node in nodes) {
body = hightlighter(body, node.InnerText);
}
到目前为止,我还无法在XSLT中做到这样的事情,但我还是个新手,所以... ;)
编辑:为了澄清一下;我要求的输出是这样的:
Somebody named <strong>Doris</strong> and <strong>Arnie</strong>