How can i find, with XSLT, the word before and after another know word in a text node?
A:
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="', 	 '"/>
</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
Dimitre Novatchev
2010-05-31 16:44:22