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?

0

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

Comments

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?

2 Comments

It was my fault - parser hid tags. I've added proper formating. I use PHP DOM extension ua.php.net/manual/en/book.dom.php and it seems this extension provides weak implementation of XPath
Did you try //div[@class='test'][position()=2]

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.