same attribute, different value for xpath

29 views Asked by At

I'd like to know if it is possible to make xpath with same attribute but different values shorter, than explicitly say @attributeName all the time. Example - I have two pages with firstName input, in one page it is

//*[@name='first'] 

and in the other

//*[@name='firstName'] 

. So a shared xpath is

//*[@name='first' or @name='firstName']

Is there any way to make it shorter like

//*[(@name)='first' or 'firstName']

I tried different ways of handling that using brackets, but no luck so far.

1

There are 1 answers

0
Conal Tuohy On BEST ANSWER

It depends on which version of XPath you are using. In XPath 2.0 or later you could write the expression like this:

//*[@name = ('first', 'firstName')]

The parenthetical expression ('first', 'firstName') defines a sequence of two strings, and the boolean expression @name = ('first', 'firstName') is a kind of general comparison in which the value of the name attribute is compared to the items in the sequence using the = operator, and which returns true if the attribute is equal to any of the values in the sequence, or false if it equals none of the values in the sequence.

In XPath 1.0 I don't know of any simpler way to write the expression than the way you've already used. I mean, you could use:

//*[contains(@name, 'first')]

... but that could also catch other values of @name, such as firstAddress, etc.