191

There is an HTML file (whose contents I do not control) that has several input elements all with the same fixed id attribute of "search_query". The contents of the file can change, but I know that I always want to get the second input element with the id attribute "search_query".

I need an XPath expression to do this. I tried //input[@id="search_query"][2] but that does not work. Here is an example XML string where this query failed:

<div>
  <form>
    <input id="search_query" />
   </form>
</div>

<div>
  <form>
    <input id="search_query" />
  </form>
</div>

<div>
  <form>
    <input id="search_query" />
  </form>
</div>

Keep in mind that that the above is merely an example and the other HTML code can be quite different and the input elements can appear anywhere with no consistent document structure (except that I am guaranteed there will always be at least two input elements with an id attribute of "search_query").

What is the correct XPath expression?

3
  • 1
    Good question, +1. See my answer for a complete explanation of the problem and for the wanted solution. Commented Oct 24, 2010 at 15:43
  • 11
    Minor point: you should never have more than one element with a given ID (and so the HTML in the question is actually invalid). In practice, browsers will let you do it anyway, but if you do you're missing out on the only benefit of using IDs, which is that they signal "I'm unique" (whereas classes are designed to be used for non-unique signifiers). Commented Sep 16, 2016 at 20:40
  • Not a minor point @machineghost ! It is actually a bug! ID stands for unique identifier! Commented Nov 23, 2021 at 10:09

2 Answers 2

362

This is a FAQ:

//somexpression[$N]

means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:

(//input[@id="search_query"])[2]

Remember: The [] operator has higher precedence (priority) than the // abbreviation.

4
  • 11
    I like this answer. I had not considered a precedence issue (I just assumed simple left-to-right precedence).
    – rlandster
    Commented Oct 24, 2010 at 16:30
  • 16
    @rlandster: The word "precedence" may be confusing. The unabbreviated form of //input[@id='search_query'][2] is: /descendat-or-self::node()/child::input[attribute::id='search_query'][position()=2]
    – user357812
    Commented Oct 24, 2010 at 20:35
  • 54
    For those who got here from Google - the numbering starts from 1 - [1] being the first element and so on
    – Jan Mares
    Commented Dec 7, 2018 at 15:45
  • 1
    The word "precedence" may be confusing but XPath does have precedence, and using parentheses is an effective way of controlling precedence: "A primary expression may also be created by enclosing any expression in parentheses, which is sometimes helpful in controlling the precedence of operators." Commented Mar 20 at 22:40
32

This seems to work:

/descendant::input[@id="search_query"][2]

I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.

There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification that provided a clue.

Compare what works:

/descendant::input[@id="search_query"][2]

to what does not work:

//input[@id="search_query"][2]

The difference is /descendant:: vs //. Consider what "//" means:

A "//" at the beginning of a path expression is an abbreviation for the initial steps (fn:root(self::node()) treat as document-node())/descendant-or-self::node()

And consider the difference between descendant and descendant-or-self:

The path expression //para[1] does not mean the same as the path expression /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 respective parents.

It's probably because the "context position" changes with descendant-or-self but doesn't change with descendant:

The context position is the position of the context item within the sequence of items currently being processed. It changes whenever the context item changes.

3
  • 2
    Many thanks for this answer. In my case the accepted solution would not work as I'm using the xpath in robot framework, which wouldn't accept paths starting with brackets. This one however, should do the trick
    – dahui
    Commented Sep 23, 2015 at 10:40
  • When I try this: ${el_my_value}= XML.Get Element ${x} .//isbn
    – LTL
    Commented Oct 21, 2021 at 9:22
  • It leads to this: Multiple elements (6) matching './/isbn' found. how can I find the 4th?
    – LTL
    Commented Oct 21, 2021 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.