1

I am using the xpath with Selenium web driver Java to locate an element using id and it's id is like this:

name\params\etc

to represent this in java, I am using

String id = "\\name\\params\\etc"
driver.findElement(By.xpath("//"+"a"+"[@id='"+id+"']"));

please let me know how to resolve it.

Vinit Sharma
  • 461
  • 2
  • 8
  • 16

3 Answers3

2

You don't need to do anything special to use backslashes in XPath. Backslashes have no special meaning in XPath, and as such, there is no way to escape them (and no need to).

What you've said is confusing. You say that the IDs are like "name\params\etc" (no slash at the beginning), but then you have "\\name\\params\\etc" (slash at the beginning). Which is it?

Have you tried this:

String id = "name\\params\\etc"
driver.findElement(By.xpath("//a[@id='" + id + "']"));
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • You were right...I mistyped the id value here..so it wasn't the issue. The element was in the inner frame and I was checking the element in main body. BTW Thanks for ur help – Vinit Sharma Apr 13 '14 at 16:06
0

Probably this is what you are looking for :

driver.findElement(By.xpath("//"+"a"+"[@id='"+id.substring(2)+"']"));

or you can try :

driver.findElement(By.xpath("//"+"a"+"[@id='"+id.replace("\\","\")+"']");

Depends on expected result - which backslash you want escape?

To make exact given id from defined id string you can follow something like this :

driver.findElement(By.xpath("//"+"a"+"[@id='"+id.substring(2).replace("\\","\")+"']"));
kch
  • 1
  • 2
0

Do you have to use Xpath? Your selector can be expressed as CSS, which may not have the same escaping issues. I haven't tried this so cannot guarantee it is a valid CSS selector.

String id = "\\name\\params\\etc";
driver.findElement(By.css("a[id='"+id+"']"));

Personally I would use string formatting to construct the string rather concatenation but that us personal choice.

You could also try this selector as well, but think that it may fail because "\" is not valid HTML id;

String id = "\\name\\params\\etc"
driver.findElement(By.css("a#"+id));
Robbie Wareham
  • 3,380
  • 1
  • 20
  • 38