Simple XPath question about root node
I have just started learnin开发者_开发问答g XPath and I am learning the language without the abbreviation first.
When a location path starts with the character '/' the initial context node is forces to be the root node...
Sample xml from book:
<widget type="gadget">
...
</widget>
If I am supposed to write the XPath so I get the type attribute why do I have to write:
/child::widget/attribute::type
and not like this /attribute::type
Have I misunderstood something about the root node or? Because I thought '/' and widget was the same...
Thank you
From http://www.w3.org/TR/xpath/#attribute-nodes
Each element node has an associated set of attribute nodes; the element is the parent of each of these attribute nodes; however, an attribute node is not a child of its parent element.
Only element nodes have attributes.
The root node is not an element. From http://www.w3.org/TR/xpath/#root-node
The root node is the root of the tree. A root node does not occur except as the root of the tree. The element node for the document element is a child of the root node. The root node also has as children processing instruction and comment nodes for processing instructions and comments that occur in the prolog and after the end of the document element.
Thus you cannot select attributes of the root node like in /@*
or /attribute::*
You ask:
Have I misunderstood something about the root node or?
Yes. You should not confuse the root node (an abstraction) with the document element (some times also called the element root)
If I am supposed to write the XPath so I get the type attribute why do I have to write:
/child::widget/attribute::type
and not like this
/attribute::type
The XPath expression:
/attribute::type
means:
Select the type
attribute of the root node of the XML document.
However, a root node doesn't have attributes (as per W3C Spec), therefore, the above XPath expression selects nothing.
You want:
/widget/@type
This means:
Select the type
attribute of the top element (named widget
) of the XML document.
Have I misunderstood something about the root node or? Because I thought '/' and widget was the same...
Always remember that the root node /
is not an element. as per the W3C XPath Spec.
精彩评论