Parsing HTML Table in C#

c# html-agility-pack html-table parsing

Question

I have an html page which contains a table and i want to parse that table in C# windows form

http://www.mufap.com.pk/payout-report.php?tab=01

this is the webpage i want to parse i have tried

> Foreach(Htmlnode a in document.getelementbyname("tr"))
{
    richtextbox1.text=a.innertext;
}

i have tried some thing like this but it wont give me in tabular form as i am simply printing all trs so please help me regarding this thanx sorry for my english.

Accepted Answer

Using Html Agility Pack

WebClient webClient = new WebClient();
string page = webClient.DownloadString("http://www.mufap.com.pk/payout-report.php?tab=01");

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);

List<List<string>> table = doc.DocumentNode.SelectSingleNode("//table[@class='mydata']")
            .Descendants("tr")
            .Skip(1)
            .Where(tr=>tr.Elements("td").Count()>1)
            .Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim()).ToList())
            .ToList();

Popular Answer

Do you mean something like this ?

foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    ///This is the table.    
    foreach (HtmlNode row in table.SelectNodes("tr")) {
    ///This is the row.
        foreach (HtmlNode cell in row.SelectNodes("th|td")) {
            ///This the cell.
        }
    }
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why