Stefan
Stefan

Reputation: 137

Adding Java variable to xpath

Is it possible to add a defined Java String variable to an xpath-expression? Here is some code to make it clear:

String newUser = "NewUser123";
driver.findElement(By.xpath("//td[normalize-space(text())=**newUser**]/a")).click();

The xpath should work with the variable newUser, but I don´t know how.

Upvotes: 6

Views: 54805

Answers (6)

Ashan Mabharana
Ashan Mabharana

Reputation: 39

Xpath with variable and space

String CasesCount = Utility.WebDriverHelper.Wdriver.findElement
(By.xpath("//button[text()=' "+tabname+"']/span")).getText();

Remove this kind of special braces () in text

CasesCount  = CasesCount.replaceAll("\\(", "").replaceAll("\\)","");

Upvotes: 3

Garima Thakur
Garima Thakur

Reputation: 11

In case if its a number in any loop table it can be written like

String sCol = "1";

driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[2]/article/div/table/tbody/tr["+sRow+"]/td["+sCol+"]")).getText();

Upvotes: 0

Kumrun Nahar Keya
Kumrun Nahar Keya

Reputation: 537

You can try the following code:

String newUser = "NewUser123";
driver.findElement(By.xpath("//td[normalize-space(text())=" + newUser + "]/a")).click();

Upvotes: 1

Nidhi
Nidhi

Reputation: 121

Yes, when you choose Java as your programming language while working with selenium, you can perform all things that are logically possible in Java.

Take your example, xpath is a function which takes string arguments. So Like in Java we concatenate multiple strings using +. you can do the same thing here.

String newUser = "NewUser123";
driver.findElement(By.xpath("//td[normalize-space(text())='"+newUser+"']/a")).click();

Upvotes: 11

Jeremiah
Jeremiah

Reputation: 1145

In similar situations I will extract the lookup to a constant in the class, and use the String.format utility to insert the variable(s) where I need it. Note the use of %s in the example constant USER_XPATH below.

I think this is better for readability and maintenance than the inline concatenation option, but both will achieve the goal.

/** Format string for the ### xpath lookup.*/
private static final String USER_XPATH ="//td[normalize-space(text())=%s]/a";

Then you can use String.format to insert the variable you want:

 private void myMethod() {
      String newUser = "NewUser123";
      String fullXpath = String.format(USER_XPATH, newUser);
      driver.findElement(By.xpath(fullXpath)).click();
    }

Upvotes: 2

Robbie Wareham
Robbie Wareham

Reputation: 3438

Treat the xpath like any other string concatenation or interpolation you would do in Java

Upvotes: -1

Related Questions