XSLT XML:突出显示搜索结果中的搜索词 [英] XSLT XML: highlight a search word in search results

查看:29
本文介绍了XSLT XML:突出显示搜索结果中的搜索词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是xml:

<?xml version="1.0" encoding="UTF-8"?>
    <file>
        <text>
            <p>
               <sentence>I bought kiwi at the grocery store.</sentence>
               <sentence>I also bought bananas at the store.</sentence>
               <sentence>Then, I bought a basket at another store.</sentence>
            </p>
            <p>
                <sentence>You bought kiwi at the grocery store.</sentence>
                <sentence>You also bought bananas at the store.</sentence>
                <sentence>Then, You bought a basket at another store.</sentence>
            </p>
        </text>
    </file>

这里是 XSLT:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="sentence">
        <p>
            <xsl:apply-templates/>
        </p>
    </xsl:template>
        <xsl:template match="/">
        <html>
            <body>
                <xsl:apply-templates select="file/text/p/sentence[contains(.,$search)]"/>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

$search="kiwi":

我在杂货店买了kiwi.

I bought <mark>kiwi</mark> at the grocery store.

你在杂货店买了kiwi.

You bought <mark>kiwi</mark> at the grocery store.

请帮忙!

推荐答案

要突出显示所有出现的搜索字符串,请更改:

To highlight all occurrences of the search string, change this:

<xsl:template match="sentence">
    <p>
        <xsl:apply-templates/>
    </p>
</xsl:template>

到:

<xsl:template match="sentence"> 
    <p> 
        <xsl:call-template name="hilite">
            <xsl:with-param name="text" select="."/>
            <xsl:with-param name="search-string" select="$search"/>
        </xsl:call-template>
    </p> 
</xsl:template> 

<xsl:template name="hilite">
    <xsl:param name="text"/>
    <xsl:param name="search-string"/>
    <xsl:choose>
        <xsl:when test="contains($text, $search-string)">
            <xsl:value-of select="substring-before($text, $search-string)"/>
            <mark>
                <xsl:value-of select="$search-string"/>
            </mark>
            <xsl:call-template name="hilite">
                <xsl:with-param name="text" select="substring-after($text, $search-string)"/>
                <xsl:with-param name="search-string" select="$search-string"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

这篇关于XSLT XML:突出显示搜索结果中的搜索词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆