Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first instance only with XPath?

Tags:

I am parsing some XML something like this:

<root>     <some_gunk/>     <dupe_node>         ...         stuff I want         ...     </dupe_node>     <bits_and_pieces/>     <other_gunk/>     <dupe_node>         ...         stuff I don't want         ...     </dupe_node>     <more_gunk/> </root> 

An XPath of '//dupe_node' will give me two instances of dupe_node to play with. I only want to traverse the first. Can I do this with XPath?

like image 492
Mat Avatar asked Jan 17 '09 11:01

Mat


People also ask

How do you select the first occurence of XPath?

Simplified Xpath syntax:/e1 -- selects the first <e1> document element (child element of the document node). /e1/e2 -- selects the first <e2> child element of the first <e1> document element. /e1[2]/e2[3] -- selects the third <e2> child element of the second <e1> document element. /e1[1]/e2[1] -- same as /e1/e2 .

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

For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.

Which button is used to find the first occurrence of the data?

The indexOf() method returns the position of the first occurrence of a value in a string.

How do I get the last child in XPath?

Locating Strategies- (By XPath- Using last())"last() method" selects the last element (of mentioned type) out of all input element present.


2 Answers

/descendant::dupe_node[1] 

//dupe_node[1] is generally wrong, although it produces an identical result in this particular case. See docs:

The location path //para[1] does not mean the same as the location path /descendant::para[1]. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents.

Given the following XML:

<foo>     <bar/>     <foo>         <bar/>     </foo> </foo> 

//bar[1] will produce two nodes, because both bars are first children of their respective parents.

/descendant::bar[1] will give only one node, which is the first of all the bars in the document.

like image 150
Azat Razetdinov Avatar answered Oct 02 '22 01:10

Azat Razetdinov


//dupe_node[1] 

XPath counts from 1, not 0 in this case. You can use this tool to try things out in your browser:

http://www.xmlme.com/XpathTool.aspx?mid=82

like image 21
Simon Willison Avatar answered Oct 02 '22 01:10

Simon Willison