XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition (420 page)

BOOK: XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition
5.61Mb size Format: txt, pdf, ePub

is really just a binary operator with a defaulted first operand. The implicit first operand in this case is the node selected by the root expression
/
. After this expansion, a rooted path behaves in exactly the same way as a relative path, which was described at the start of this chapter.

A consequence of these rules is that a rooted path such as
/X
will throw an error in all the cases where the root expression
/
throws an error. Specifically:

  • It's an error if there is no context item.
  • It's an error if there is a context item but the context item isn't a node.
  • It's an error if the context item is in a tree whose root is something other than a document node.

There's a good reason for the restriction that a rooted path expression can only be used to select within a tree that's rooted at a document node. If it were allowed to start from any kind of node, there would be some strange surprises. For example, if the root of the tree were an element node named

, then the expression
/A
would not select that element. This expression is an abbreviation for
(/)/child::A
, so it would select all elements named A that are children of the root element, but not the root element itself. Rather than allow such surprises to occur, the working group decided to make this an error. If you want to select relative to the root of a non-document tree, you can always do this with a relative path expression whose first step is a call to the
root()
function, described in Chapter 13. For example, you can select all the A elements in a tree, even an A element that is the root of the tree, with the expression
root(.)/descendant-or-self::A
.

If you want to start from the root of a different document than the one containing the context node, the simplest approach is to write a path expression whose first component is a variable reference identifying the root of the tree you want to make your selection from. This happens frequently in XSLT. If you are writing a stylesheet that loads several source documents using the
doc()
function, there is no direct way of selecting the root of the principal source document when the context node is in a different one. To solve this problem, it is useful to include in your stylesheet a global variable declaration of the form

. You can then refer to the root of the principal document at any time as
$input
, and you can select other nodes in this tree with relative path expressions of the form
$input/A/B
.

Other books

Falling For Her Boss by Smith, Karen Rose
New Regime by Laken Cane
Waiting for Morning by Karen Kingsbury
o 922034c59b7eef49 by Allison Wettlaufer
Dying to Tell by T. J. O'Connor
The Right and the Real by Joelle Anthony