5

xpath 1 : //div[@class='abc'][.="xyz"]/parent::*/div[2]/div

xpath 2 : //div[@class='abc'][.="xyz"]//following-sibling::div/div

Above two xpaths are pointing same element. Which is better and why, Can anyone please describe ?

5

The two paths might give the same result on one sample document, but they will give different results on other documents. The one that is best is the one that gives the right results over a whole class of documents. Without knowing anything about the structure and semantics of the class of documents you want to apply these expressions to, it's impossible to say which is best.

If you're only going to apply the expression to one source document, then your question is like asking whether (42+3) or (9*5) is a better way of getting to 45. (You already know the answer, so why compute it?)

Having said that, I strongly suspect that in the second expression, the // before following-sibling should be /. With that change, the two expressions are equivalent for some documents: specifically those documents where the div selected by [@class='abc'][.="xyz"] is the first of exactly two div children of its parent.

3

Both xpaths are bad because they are logically not obvious.

If to choose between your two I would say that the first is better because the second one is probably doing not exactly what you expect since you're using double slash before following-sibling, hence you're choosing among not only sibling but all the nested elements as well.

The more logically strucutred way in your case would be:

//*[div[@class='abc'][.="xyz"]]/div[2]/div
3

In my opinion, both are fragile as depending on physical static hierarchy("/div") of the DOM which may easily change in subsequent Dev changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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