Thursday, July 19, 2012

Selenium 2 Java client: How to resolve apostrophes problem in xPath

It's pretty much common problem how to handle apostrophes if you have to use them in attribute values or any text which you somehow  use to narrow the search scope.

Assume we need to find the element having name attribute containing pattern "Someone's". Like

<file name="Someone's name"/>

The obvious way is to use the xPath like this: //file[contains(@name,'Someone's')]. However such the xPath won't be parsed properly as we've just broken the language syntax by placing three sequential single-quotes.

The good approach to resolve such the problem is to use the concat construction so that the example above will look like this:

//file[contains(@name,concat('Someone',"'",'s'))]

Here we split the string by three parts and enclosed the single-quote with double-quotes. This is the good solution, however we still need the approach to build such the constructions whatever the number of single-quotes have the place and whatever combination with regular text they have as well

Fortunately Java provides convenient facility to work with the strings and here I suggest the function helping to handle such the problem in your Selenium scenario.

 String resolveAprostophes(String item){
  if(!item.contains("'")){
   return "'" + item + "'";
  }
  StringBuilder finalString = new StringBuilder();
  finalString.append("concat('");
  finalString.append(item.replace("'", "',\"'\",'"));
  finalString.append("')");
  return finalString.toString();
 }
So you can use it in such the way:

String safeXPathToLocateTheElement = "//file[contains(@name," + resolveAprostophes("Someone's") + ")]";

And then use it in your regular look-up patterns