Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting first node in xpath result set

Tags:

xpath

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.

like image 667
tipu Avatar asked Feb 08 '12 18:02

tipu


People also ask

How do I select the first child in XPath?

The key part of this XPath is *[1] , which will select the node value of the first child of Department .

How do you select the second element with the same XPath?

//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.

What does * indicate in XPath?

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.

How do I navigate to parent node in XPath?

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.


1 Answers

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] 
like image 118
Wayne Avatar answered Sep 20 '22 04:09

Wayne