Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first result in XPath

Tags:

xpath

I've looked at this question: Select first instance only with XPath?

But if I have a node-set like this:


<container value="">
  <data id="1"></data>
  <data id="2">test</data>
  <container>
    <data id="1">test</data>
    <data id="3">test</data>
  </container>
</container>

Now my scenario is that this node-set is deep inside a document, and I have a pointer to the inner container. So I have to prefix my XPath with "/container/container" (the path is actually longer, but for this example this should do).

EDIT: What I want is a "data" node with an id of 1, which should come from the lowest node first or the closest ancestor. So, if I can't find it on the "current" (/container/container) I should look at the ancestors and get the nearest one (or in the end, not find anything). I have tried this:

/container/container/ancestor-or-self::container/data[@id="1"]

Which brings back a result set with two nodes. I thought I could use last() to get the deepest one, so I tacked that on the end, but to no avail.

like image 581
Nick Spacek Avatar asked May 21 '09 11:05

Nick Spacek


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

try [position()=1]

ex.

/container/container/ancestor-or-self::container/data[position()=1]

like image 65
user3121414 Avatar answered Dec 05 '22 11:12

user3121414


Make sure the last() is scoped correctly. Try:

(/container/container/ancestor-or-self::container/data[@id="1"])[last()]

Similarly:

//container[last()]

and:

(//container)[last()]

are not the same thing. The first will return the last container node at each level of the hierarchy - multiple matches - and the second will return the last container node found - one match.

like image 36
Dave Webb Avatar answered Dec 05 '22 11:12

Dave Webb