I am trying to select the first element in a set of resulting nodes after executing an xpath query.
When I do this:
//dl
I get the following result set:
[<dl>…</dl>, <dl>…</dl>]
How can I get the first one? Neither of these work:
//dl[1] //dl[position()=1]
I am executing this in Chrome's Web Inspector.
The key part of this XPath is *[1] , which will select the node value of the first child of Department .
//div[@class='content'][2] means: Select all elements called div from anywhere in the document, but only the ones that have a class attribute whose value is equal to "content". Of those selected nodes, only keep those which are the second div[@class = 'content'] element of their parent.
The XPath default axis is child , so your predicate [*/android.widget.TextView[@androidXtext='Microwaves']] is equivalent to [child::*/child::android.widget.TextView[@androidXtext='Microwaves']] This predicate will select nodes with a android. widget. TextView grandchild and the specified attribute.
A Parent of a context node is selected Flat element. A string of elements is normally separated by a slash in an XPath statement. You can pick the parent element by inserting two periods “..” where an element would typically be. The parent of the element to the left of the double period will be selected.
Use the following:
(//dl)[1]
The parentheses are significant. You want the first node that results from //dl
(not the set of dl
elements that are the first child of their parent (which is what //dl[1]
(no parens) returns)).
This is easier to see when one realizes that //
is shorthand for (i.e. expands fully to) /descendant-or-self::node()/
so that //dl[1]
is equivalent to:
/descendant-or-self::node()/dl[1]
...which is more obviously not what you want. Instead, you're looking for:
(/descendant-or-self::node()/dl)[1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With