I'm writing an automated test for a page where the contents are partially randomized: the text of an element will be one of a known set of possibilities.

I want to write an XPath selector that says: "there's an <h3> whose contents are either Foo or Bar or Baz".

How would I do that?

I think I need a regular expression and matches. I've tried //h3[matches(text(), 'Foo|Bar|Baz|')]', but the library I'm using says that's not a valid query. (I don't know what version of XPath it uses.)

  • 1
    You should write it as //h3[text() = 'Foo' or text() = 'Bar' or text() = 'Baz'] – Wiktor Stribiżew Oct 30 '17 at 13:42
up vote 2 down vote accepted

Regular expressions and the matches() function require XPath 2.0.

If your library only supports XPath 1.0, then use this XPath,

//h3[.='Foo' or .='Bar' or .='Baz']

to select all h3 elements whose string value is one of Foo or Bar or Baz without needing to use regular expressions.

Using XPath 2.0 and later you can also use //h3[. = ('Foo', 'Bar', 'Baz')] if you simply want to compare the string contents of the h3 element to those three values in the sequence.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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