8 July 2007 - Getting the text value of a node with XPath
XPath's text() function is used to retrieve the text value of a node. Consider the following XML:
<categories>
<category>Entertainment</category>
<category>Sport</category>
<category>Trivia</category>
</categories>To assign the "Sport" category to a variable you can use this expression:
<xsl:variable name="sport" select="/categories/category[text() = 'Sport']" />
That XPath expression can be read as: "Look at the root 'categories' node and select the child 'category' node such that its text content is equal to 'Sport'".
In fact, it's possible to rewrite the above example without even using the text() function:
<xsl:variable name="sport" select="/categories/category[. = 'Sport']" />
In this version the predicate (within the square brackets) uses the "self" axis (the dot) to examine the category node. Examining the node returns its text content, which can then be compared to the 'Sport' string.