Newcomer
Newcomer

Reputation: 503

Xpath selector difference: pros and cons

I have two xpath selectors that find exactly the same element, but I wonder which one is better from code, speed of execution, readability points of view etc.

First Xpath :

//*[@id="some_id"]/table/tbody/tr[td[contains(., "Stuff_01")]]//ancestor-or-self::td/input[@value="Stuff_02"]

Second Xpath:

//tr[td[@title="Stuff_01"]]//ancestor-or-self::td/input[@value="Stuff_02"]

The argument for example is that if the code of the page will be changed and for example some "tbody" will be moved that the first one won't work, is it true ? So any way which variant of the code is better and why ?

I would appreciate an elaborate answer, because this is crucial to the workflow.

Upvotes: 2

Views: 629

Answers (1)

kjhughes
kjhughes

Reputation: 111541

It is possible that neither XPath is ideal. Seeing the targeted HTML and a description of the selection goal would be needed to decide or to offer another alternative.

Also, as with all performance matters, measure first.

That said, performance is unlikely to matter, especially if you use an @id or other anchor point to hone in on a reduced subtree before further restraining the selection space.

For example, if there's only one elem with id of 1234 in the document, by using //elem[@id="1234"]/rest-of-xpath, you've eliminated the rest of the document as a performance/readability/robustness concern. As long as the subtree below elem is relatively tame (and it usually will be), you'll be fine regarding those concerns.

Also, yes, table//td is a fine way to abstract over whether tbody is present or not.

Upvotes: 2

Related Questions