代码之家  ›  专栏  ›  技术社区  ›  Matteo

XSLT在另一个单词附近查找单词

  •  1
  • Matteo  · 技术社区  · 16 年前

    使用XSLT,如何在文本节点中查找另一个已知单词前后的单词?

    1 回复  |  直到 16 年前
        1
  •  0
  •   Dimitre Novatchev    16 年前

    一、 在XSLT 2.x/xpath2.x中,可以使用函数 tokenize() index-of() 使用一行XPath表达式生成所需的结果 :

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

    当此转换应用于以下XML文档时 :

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

    得到想要的正确结果 :

    two four
    

    二。XSLT 1.0解决方案

    可以使用 strSplit-to-Words 模板 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>
    

    当此转换应用于同一XML文档时 :

    <t>一、二、三、四<t>
    

    得到想要的正确结果 :

    二四