-2

I want to build a String from text that I've grabbed from WebElements using WebDriver.

public String getTextFromWebElements() {
    String stringOne= null;
    List<WebElement> listOfWebElements = driver.findElements(By.cssSelector(".events-stuff-morestuff"));
    for (WebElement we : listOfWebElements) {
        stringOne= we.getText();
    }
    return stringOne;
}

I want stringOne to build a String containing a concatenated list of all the text from the WebElements, not the last one in the loop (as it does currently). Then I will split them out in the code which calls this method, so I can do an Assertion against data from an API.

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Steerpike
  • 1,712
  • 6
  • 38
  • 71
  • possible duplicate of [How do I concatenate two strings in Java?](http://stackoverflow.com/questions/3753869/how-do-i-concatenate-two-strings-in-java) – Chad Nouis Sep 14 '15 at 16:17

1 Answers1

-1
  1. You problem is you override stringOne value each iteration: stringOne= we.getText();
  2. Never concatenate a String inside a loop in Java, for this use StringBuilder.
  3. I used char COMMA ',' as SEPARATOR for data, but you can use any just replacing it inside loop. Just note you must initialize char with empty value: char SEPARATOR = '\0';.

public String getTextFromWebElements() {
        StringBuilder stringOne = new StringBuilder();
        List<WebElement> listOfWebElements = driver.findElements(By.cssSelector(".events-stuff-morestuff"));
        char SEPARATOR = '\0';
        for (WebElement we : listOfWebElements) {
            stringOne.append(SEPARATOR);              
            stringOne.append(we.getText());
            SEPARATOR = ',';
    }
    return stringOne.toString();
}
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • Ok, 2 answers which work - thank you both. Can I ask how to initialise the empty char without getting an 'empty character literal' error? – Steerpike Sep 14 '15 at 15:37
  • @Steerpike sorry, I've written the answer on the fly, just use `String SEPARATOR = ""` or `char SEPARATOR = '\0';` (empty char value) – Jordi Castilla Sep 14 '15 at 15:40