Read XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition Online
Authors: Michael Kay
root(self::node()) treat as document-node()
This means that it selects the same node as the
root()
function described in Chapter 13, when given the context node
self::node()
as an argument, but raises an error if this node isn't a document node (the
treat as
expression is covered in Chapter 11).
Various errors can arise if you use the
/
expression inappropriately:
The language could have been designed so that
/
was a synonym of the axis step
ancestor-or-self::node()[last()]
, which selects the root of the tree whatever kind of node it is. The designers decided not to do this to avoid the surprises that can otherwise occur if you find yourself at a different kind of node from the one you were expecting. This decision also has the advantage that the type of the expression
/
is known more precisely: it always returns a document node, which means that it is always safe to use it in contexts (such as a call to a user-defined function) where a document node is the required type.
Although I have classified the root expression as an abbreviated axis step, it's unusual to use it explicitly as an operand of the
/
operator. Unusual, but not illegal. You will usually need to put it in parentheses if you try it; for example,
$x/(/)
selects the document node at the root of the tree containing the node
$x
. A unary
/
operator appearing in an expression such as
/book/chap/title
can be seen as an abbreviation for
(/)/book/chap/title
, so the root expression is being used as an implicit axis step whenever you write a path expression starting with
/
. Which forms the subject of the next section… .