Determining the Current Node
A node in a node-set becomes the current node as a result of the implicit looping to process all nodes of a certain kind in an <xsl:apply-templates>
or <xsl:for-each>
element. You can always access the current node, using the current()
function. This will be identical to the context node and can be represented in an XPath expression as "." (a single period, which is the abbreviated syntax for self::node()
).
The one exception may be when a node is referenced in the predicate of an XPath expression. The context node remains the node currently being processed in the node-set, while the current node temporarily shifts depending on the XPath expression in the predicate.
The two XSLT template rules in the XSLT sample file below recursively walk through the document, displaying the context node, the current node, and the value of all elements in weather.xml.
The formatted output below shows that the context node and the current node are the same all the way through the document.
Example
XML File (weather.xml)
Change the href
attribute in weather.xml (shown in Sample XML Data File for XPath Context and Navigation) to reference weathercurrnode.xsl.
XSLT File (weathercurrnode.xsl)
<?xml version='1.0'?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <table border="1"> <tr> <th>Context</th><th>Current</th><th>Node value</th> </tr> <xsl:apply-templates/> </table> </xsl:template> <xsl:template match="*"> <tr> <!-- Display context node's name --> <td><xsl:value-of select="name()"/></td> <!-- Display current node's name --> <td><xsl:value-of select="name(current())"/></td> <!-- Display node's value --> <td><xsl:value-of select="."/></td> </tr> <!-- Recurse through ELEMENT children of the current node. (Without select="*", ALL children are selected. This causes the text nodes to display in a list apart from the table.) --> <xsl:apply-templates select="*"/> </xsl:template> </xsl:stylesheet>
Formatted Output
Processor Output
A portion of the processor output is shown here, with line breaks added.
<?xml version="1.0" encoding="UTF-16"?> <table border="1"> <tr><th>Context</th><th>Current</th><th>Node value</th></tr> <tr><td>weather</td><td>weather</td><td> 76 67 5 81 30 10 Rain 72 60 2 Fog </td></tr> <tr><td>today</td><td>today</td><td> 76 67 5 </td></tr> ... </table>
See Also
Using Abbreviations in XPath Expressions