Jefe infiltrado
Jefe infiltrado

Reputation: 382

Xpath with Ancestor with multiple tag names

I want generic xpath to get a button to add an item to the shopping bag depending on the product name.
So far this is quite easy, I get the element with the product name, go bag to the root of the container and then look for the button:

//*[contains(text(),'productname')]//ancestor::article//div[contains(@id,'AddToBagButton')]

But now things became more difficult since there are several layouts for the same container which do have different tags for the root element. In looking for how to express this I came up with this solution:

//*[contains(text(),'productname')]//ancestor::*[local-name()='article' or local-name='product']//div[contains(@id,'AddToBagButton')]

But unfortunately, this works only for the first local-name()='article' and not for the second local-name='product'.

Is there any way to cover both cases?

Upvotes: 1

Views: 295

Answers (1)

Prophet
Prophet

Reputation: 33361

You can locate the mutual parent node based on known child (productName) and then to find another child inside it (AddToBagButton) as following:

//*[local-name()='article' or local-name='product'][.//*[contains(text(),'productname')]]//div[contains(@id,'AddToBagButton')]

Also, since the productName is text content, we can reduce the above expression to the as following:

//*[local-name()='article' or local-name='product'][contains(.,'productname')]//div[contains(@id,'AddToBagButton')]

Upvotes: 1

Related Questions