Current node versus node context in XSLT / XPath?

In XSLT, what is the difference between “current node” and “node context”? You can find both terms used here: http://www.w3.org/TR/xslt .

When will you use this or that? How do you feel about everyone?

+61
xml xpath xslt
Jun 20 '09 at 19:29
source share
1 answer

The current node works no matter which template works. Usually this is also the node context, but the node context has special meaning inside the nested XPath expression (part in square brackets). There he refers to the fact that node is currently being tested for compliance. Therefore, the context of the node changes in the XPath expression, but not in the current node.

The node context may be abbreviated with a period ( . ) Or sometimes completely excluded. This is probably a bit confusing because outside the nested expression, the dot denotes the current node. (In this case, the current node is the node context, so we can say that it is the current node only closer, and it is more correctly called the node context. But even spec calls are the current node here.)

Since the dot gives you the context of the node, in a nested XPath expression, the user needs a way to return to the current node, which is being processed by the current template. You can do this using the current() function.

The difference between the two is useful in some cases. For example, suppose you have XML like this:

 <a> <b> <c>foo<footnote fn="1"/></c> <d>bar</d> </b> <b> <c>baz</c> <d>aak<footnote fn="2"/></d> </b> <b> <c>eep</c> <d>blech<footnote fn="2"/></d> </b> <footnote-message fn="1">Batteries not included.</footnote> <footnote-message fn="2">Some assembly required.</footnote> </a> 

Now suppose you want to convert it to LaTeX as follows:

 foo\footnote{Batteries not included.} bar baz aak\footnote{Some assembly required.} eep blech\footnotemark[2] 

The trick is to say whether a footnote has already been used or not. If this is your first encounter with a footnote, you want to write the \footnote command; otherwise, you want to write the \footnotemark command. You can use the XSL code as follows:

 <xsl:choose> <xsl:when test="count(preceding::*[./@fn = current()/@fn]) = 0">\footnote{...}</xsl:when> <xsl:otherwise>\footnotemark[...]</xsl:otherwise> </xsl:choose> 

Here we compare the context- node fn attribute (from the results of preceding::* node -set) with the current- node fn attribute. (You really shouldn't say ./@fn , you can just say @fn .)

So, the node context leaves you inside the XPath predicate; the current node goes beyond the predicate, back to the node processed by the current template.

+68
Jun 20 '09 at 19:30
source share



All Articles