None of the above approaches cover a situation where both Quote and Apostrophe cos exist. I've created a function for that,
driver.findElements(By.xpath(String.format("//input[contains(@text,%s))]"),escapeQuotes(textVal));
Implemenatation of the escape Quote.
private String escapeQuotes(String text) {
// If we don't have any Quote then enquote string in Quote
if (!text.contains("\"")) {
return String.format("\"%s\"", text);
}
// If we have some Quote but no Apostrophe then enquote in Apostrophe
if (!text.contains("'")) {
return String.format("'%s'", text);
}
// If input is like Administr"ati'on then we have both " and ' in the string so must use Concat
// we will be building the xPath like below and let the browser xPath evaluation to handle the concatenation
// output : concat('Administr\"',\"ati'on\")
StringBuilder sb = new StringBuilder("concat(");
// Looking for " as they are LESS likely than '
int lastPos = 0;
int nextPos = text.indexOf("\"");
while (nextPos != -1) {
// If this is not the first time through the loop then seperate arguments with ,
if (lastPos != 0) {
sb.append(",");
}
sb.append(String.format("\"%s\",'\"'", text.substring(lastPos, nextPos - lastPos)));
lastPos = ++nextPos;
// Find next occurrence
nextPos = text.indexOf("\"", lastPos);
}
sb.append(String.format(",\"%s\")", text.substring(lastPos)));
return sb.toString();
}