Sandesh Sawant
Sandesh Sawant

Reputation: 109

What's the difference between "/node()" and "node()" in XPath?

As per my understanding of XPath, for any HTML or XML document:
$x("/node()") means $x("/child::node()") which means return the node which is a child of the context node. Here, the root node(/) is the context node. Therefore, it returns the html element.

$x("node()") means $x("child::node()") which also returns the same html element. But in this case, we have not provided the context node unlike in the above case. So, how does it identify the context node in this case ?

Also, are both the above XPath expressions syntactically and functionally same.

Upvotes: 2

Views: 337

Answers (1)

kjhughes
kjhughes

Reputation: 111726

The difference is that /node() specifies the context node absolutely as the document root (/), but node() relies upon an implied, relative context node.

How is an implied, relative context node determined? Well, based on context. ;-) For example, the hosting language will typically set the initial context node to the current node being matched or iterated. Then, within the evaluation of the XPath itself, each location step (separated via slashes, /) establishes the context node for the subsequent steps.

The $x(path, [startNode]) notation used in the Chrome console takes an optional second argument that can be used to specify the context node explicitly. By default, it is equal to the document root node, which leads to the observed behavior where $x("node()") and $x("/node()") returned the same results for a given document.

Also, are both the above XPath expressions syntactically and functionally same.

Clearly node() and child::node() are syntactically different, but, yes, they are semantically (or functionally, as you say) the same because the child:: axis is the default axis.

See also

Upvotes: 1

Related Questions