XSLT XML:在搜索结果中突出显示搜索词

史蒂夫·杜(Steve DEU)

这是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在结果中突出显示该单词$search="kiwi"

在杂货店买了<mark>猕猴桃</mark>

在杂货店买了<mark>猕猴桃</mark>

请帮忙!

michael.hor257k

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

<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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章