stan
stan

Reputation: 81

Selenium C# Tables - reading each values and adding them and Returning as List<string>

I can able to read the table values BUT Im unable to add the values inside foreach loop and returning them as List<string>.

Please share your approach and Will be great helpful

IWebElement tableElement = driver.FindElement(By.XPath("//div[@id='table']"));
IList<IWebElement> tableRow = tableElement.FindElements(By.TagName("tr"));
IList<IWebElement> rowTD;

foreach (IWebElement row in tableRow)
{
    rowTD = row.FindElements(By.TagName("td"));
    //add the values in list?? 
}

return list

After this how can I add the td text values into an List<string>? I want this function to return the list.

Upvotes: 2

Views: 1614

Answers (2)

Michiel Bugher
Michiel Bugher

Reputation: 1075

I'm guessing that you are trying to return all of the table data elements as a list of strings. If you want to stick with a similar approach of only getting the text of the td elements, then I would do something like this:

IWebElement tableElement = driver.FindElement(By.XPath("//div[@id='table']"));
IList<IWebElement> tableDataElements = tableElement.FindElements(By.TagName("td"));

var reults = new List<string>();

foreach (IWebElement tableDataElement in tableDataElements)
{
    var tableData = tableDataElement.Text;
    reults.Add(tableData);
}

return reults;

Upvotes: 2

Richard II
Richard II

Reputation: 871

You can combine Michiel's answer with LINQ to do this even more concisely--without a foreach loop at all:

First, add

using System.Linq;

Then, you can replace your entire code block with:

return driver.FindElement(By.XPath("//div[@id='table']"))
          .FindElements(By.TagName("td"))
          .Select(e => e.Text)
          .ToList();

Upvotes: 2

Related Questions