24

I need to use apostrophe (') in my xpath expression which i need to use in finding elements using webdriver

i need to use below Xpath expression

//input[@text="WE'd like to hear from you"]

while using the above expression in find elements function i am replacing double quotes with single quotes

driver.findelements(By.xpath("//input[@text='WE'd like to hear from you']"))
har07
  • 88,338
  • 12
  • 84
  • 137
dolittle
  • 310
  • 1
  • 5
  • 13

7 Answers7

33

Use the xpath as shown below:

driver.findElements(By.xpath("//input[contains(@text,\"WE'd\")]"));

Hope this helps.

David Spence
  • 7,999
  • 3
  • 39
  • 63
k.s. Karthik
  • 731
  • 6
  • 16
7

You have to use double-quotes as your XPath string literal delimiter, since XPath 1.0 doesn't provide a way of escaping quotes. In addition to that, you can escape the double-quotes in Java, to avoid it from conflicting with your Java string delimiter, which also use double-quotes :

driver.findelements(By.xpath("//input[@text=\"WE'd like to hear from you\"]"))
har07
  • 88,338
  • 12
  • 84
  • 137
4

The Escape character usage does not serve the purpose. I tried the concatenation function and it worked like a charm. Please see the below xpath.

tag: li Manager of Workflow Initiator's Manager /li

Concatenate function and split the string as –

concat('Manager of Workflow Initiator',"'",'s Manager')

Single quote is kept in double quote while other characters are kept in single quotes..

So XPath looks as –

//li[.=concat('Manager of Workflow Initiator',"'",'s Manager')]
Nakilon
  • 34,866
  • 14
  • 107
  • 142
Moin
  • 71
  • 1
  • if the above solution doesn't work then use the below solution using escape sequence. xpath: //li[.=\"Manager of Workflow Initiator's Manager\"] Here we are treating the whole text as a string. – Moin Oct 05 '17 at 12:02
  • This is a great general solution that can be used for a function that will escape arbitrary strings that might contain single and double quotes. – Karen Zilles Aug 23 '22 at 18:11
1

if the above solution doesn't work then use the below solution using escape sequence.

xpath: //li[.=\"Manager of Workflow Initiator's Manager\"]

Here we are treating the whole text as a string using the escape character

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Moin
  • 71
  • 1
0

I Encountered a similar situation where I need to write an xpath for an element shown below:

Element:

<img src="webwb/pzspacer.gif!!.gif" class="inactvIcon" data-ctl="["DatePicker"]" style="cursor:pointer;">

I was able to grep the element using below Xpath, where I used the backslash to escape the characters [ and ".

Xpath : //img[@data-ctl='\[\"DatePicker\"\]']

Hope this helps.

3ven
  • 1
  • 1
0

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();
}
Gayan Kavirathne
  • 2,909
  • 2
  • 18
  • 26
0

I'm working with c# and Selenium, only way that worked for me was by splitting the string at (') and combine them using concat function. This is a small method I used to achieve my goal.

This method takes two input parameters: inputString and originalXpath.

If inputString does not contain any single quotes, the method simply returns the originalXpath string formatted with the inputString parameter using the string.Format() method.

If inputString does contain single quotes, the method replaces each single quote with ', "'", ' using the Replace() method and concatenates the resulting string with the concat() function. It then replaces the placeholder ' {0} ' in the originalXpath string with the replacementString created in the previous step using the Replace() method. Finally, the method returns the resulting string.

In summary, this method formats an XPath string with an input parameter, using a concat() function to handle cases where the input parameter contains single quotes.

using System;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        string originalXpath = "//div[contains(., '{0}')]";
        string inputString = "bjhe'bf83785*^{}^$#%!'edferferf'034**()";
        string output = FormatWithConcat(inputString, originalXpath);
        Console.WriteLine(output); 
        // Output: //div[contains(., concat('bjhe', "'", 'bf83785*^{}^$#%!', "'", 'edferferf', "'", '034**()'))]
    }
    
    private static string FormatWithConcat(string inputString, string originalXpath)
    {
        if (!inputString.Contains('\''))
        {
            return string.Format(originalXpath, inputString);
        }
        
        string replacementString = "concat('" + inputString.Replace("'", "', \"'\", '") + "')"; // Replace single quotes and concatenate with 'concat' function
        string finalString = originalXpath.Replace("'{0}'", replacementString); // Replace the placeholder '{0}' in the original XPath with the replacement string
        return finalString;
    }
}

Equivalent Java code is:

public static String FormatWithConcat(String inputString, String originalXpath) {
    if (!inputString.contains("'")) {
        return String.format(originalXpath, inputString);
    }

    String replacementString = "concat('" + inputString.replaceAll("'", "', \"'\", '") + "')";
    String finalString = originalXpath.replace("'{0}'", replacementString);
    return finalString;
}

.NET Fiddle

Nishan
  • 3,644
  • 1
  • 32
  • 41