开发者

XSLT find word near another word

How can i find, with XSLT开发者_Go百科, the word before and after another know word in a text node?


I. In XSLT 2.x / XPath 2.x one can use the functions tokenize() and index-of() to produce the desired results with one-liner XPath expressions:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:param name="pWord" select="'three'"/>

 <xsl:template match="text()">
   <xsl:sequence select=
    "tokenize(., ',\s*')
        [index-of(tokenize(current(), ',\s*'), $pWord) -1]"/>

   <xsl:sequence select=
    "tokenize(., ',\s*')
        [index-of(tokenize(current(), ',\s*'), $pWord) +1]"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the following XML document:

<t>One, two, three, four</t>

the wanted, correct result is produced:

two four

II. XSLT 1.0 solution

It is possible to solve the same task in XSLT 1.0 using the strSplit-to-Words template of FXSL.

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:ext="http://exslt.org/common"
>
   <xsl:import href="strSplit-to-Words.xsl"/>

   <xsl:output method="text"/>

   <xsl:param name="pWord" select="'three'"/>

    <xsl:template match="/">
      <xsl:variable name="vrtfwordNodes">
        <xsl:call-template name="str-split-to-words">
          <xsl:with-param name="pStr" select="/"/>
          <xsl:with-param name="pDelimiters" 
                          select="', &#9;&#10;&#13;'"/>
        </xsl:call-template>
      </xsl:variable>

      <xsl:variable name="vwordNodes"
         select="ext:node-set($vrtfwordNodes)/*"/>

      <xsl:variable name="vserchWordPos" select=
      "count($vwordNodes
                 [. = $pWord]/preceding-sibling::*
             ) +1"/>

      <xsl:value-of select=
       "concat($vwordNodes[$vserchWordPos -1],
               ' ',
               $vwordNodes[$vserchWordPos +1]
               )
       "/>
    </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the same XML document:

<t>One, two, three, four</t>

the wanted, correct result is produced:

two four
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜