Tuesday, June 10, 2008

self axis vs .

Andrew Welch started a nice discussion about comparison of XPath's self axis vs ., on xsl-list.

Andrew wrote that he has seen people writing self::elem//whatever instead of .//whatever.

I looked at the XPath 2.0 spec to find the relevant definitions. Below are the definitions from the XPath 2.0 spec.

the self axis contains just the context node itself

. is known as, "context item expression".
A context item expression evaluates to the context item, which may be either a node (as in the expression fn:doc("bib.xml")/books/book[fn:count(./author)>1]) or an atomic value (as in the expression (1 to 100)[. mod 5 eq 0]).

The context item is the item currently being processed. An item is either an atomic value or a node. When the context item is a node, it can also be referred to as the context node.

Wendell Piez wrote,

It also works to test whether the current node is actually an 'elem' when you process it or traverse from it.

Mukul: I personally prefer the style, .//whatever as it is shorter. But I think, there are important use cases for using the self:: axis.

Like for e.g.,

<xsl:template match="*[not(self::elem)]">
<!-- do something -->

<xsl:template match="*">
<xsl:if test="not(self::elem)">
<!-- do something -->

Vyacheslav Sedov wrote,

In XSLT 2.0 I prefer to use "* except elem".

No comments: