Search code examples
c#seleniumselenium-webdriverxpath

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.


Solution

  • 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;