2010-05-31 43 views
1

如何使用XSLT查找单词节点之前和之后的单词?XSLT找到另一个单词附近的单词

+0

很好的问题(+1)。查看我的答案以获取完整的XSLT 1.0和XSLT 2.x解决方案。 :) – 2010-05-31 17:04:36

回答

0

I.在XSLT 2.X/XPath的2.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 

II。 XSLT 1.0解决方案

有可能使用的FXSLstrSplit-to-Words模板解决XSLT 1.0相同的任务。

<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>One, two, three, four</t> 

想要的,正确的结果产生

two four 
相关问题