0

I have the folllowing piece of Java in which I want to add a String inside a statement:

     @and ("^I want to change fieldnumber \"([^\"]*)\" , remove whats inside and add the following text: \"([^\"]*)\"$")

    public void testscenario12345(String number,  String text) throws Throwable {
    driver.findElement(By.xpath("//*[contains(@name,'template:view:<INSERT NUMBER STRING HERE>:item:view:1:item:')]")).clear();
    driver.findElement(By.xpath("//*[contains(@name,'template:view:<INSERT NUMBER STRING HERE>:item:view:1:item:')]")).sendKeys(text);

How can I add the number string in the above piece of code? To clarify, If I insert "4" in cucumber, I want the driver to find the element by Xpath, where the @name contains template:view:4:item:view:1:item:

2
  • 5
    Is it not simply something like driver.findElement(By.xpath(String.format("//*[contains(@name,'template:view:%s:item:view:1:item:')]", "1"))).clear(); ...as in your question actually has nothing to do with Selenium or XPath but merely "how do I format a string in Java so I can place a variable inside it?" Commented Mar 6, 2014 at 9:27
  • I didn't know that... I am just a functional tester who has been ordered to use selenium, so I figured that xpath and selenium were both bits of neccesary information in order to get everything working. But it works great now, thanks :) Commented Mar 6, 2014 at 11:25

1 Answer 1

1

What about

driver.findElement(By.xpath("//*[contains(@name,\"template:view:" + number+ ":item:view:1:item:\")]")).clear();

And you probably need the number to be const, that means:

public void testscenario12345(final String number,  String text) throws Throwable {
Sign up to request clarification or add additional context in comments.

3 Comments

unfortunatly, doesn't work... "Illegal escape character in string literal", message under ":item:view:1:item:\"
did you try what @Arran suggested in his/her comment? The String.format solution, this should work. For your error, google for escape string
Yes, and now it works. Apparently, I misplaced a ". Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.