22

I have several nodes with some particular attribute and I need to select one of them by index. For example I need to select second <div> with 'test' class - //div[@class='test'][2] doesn't work.

Is there a way to select node with some attribute by index ? How to do it?

HongKilDong
  • 1,276
  • 3
  • 16
  • 23

2 Answers2

55

This is a FAQ.

In XPath the [] operator has a higher precedence (binds stronger) than the // pseudo-operator.

Because of this, the expression:

//div[@class='test'][2]

selects all div elements whose class attribute is "test" and who (the div elements) are the second such div child of their parent. This is not what you want.

Use:

(//div[@class='test'])[2]
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
2

I believe per XML specification, attributes are not considered to have an order.
Note that the order of attribute specifications in a start-tag or empty-element tag is not significant.
See here I think you'd be best of re-factoring your structure such that attribute order does not describe anything. If you can give any more details we might be able to offer suggestions.

EDIT: Re-reading your post, looks like you are trying to find node order and not attribute order. Node order is allowed and your syntax looks OK off-hand. What software are you doing this in?

Matt Molnar
  • 2,412
  • 3
  • 22
  • 28
  • It was my fault - parser hid tags. I've added proper formating. I use PHP DOM extension http://ua.php.net/manual/en/book.dom.php and it seems this extension provides weak implementation of XPath – HongKilDong Apr 28 '11 at 12:47
  • 1
    Did you try `//div[@class='test'][position()=2]` – Matt Molnar Apr 28 '11 at 12:50