Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of converting a Html table to datatable

Tags:

c#-3.0

I have a html table.I want to convert this into a datatable. What is the best way of doing so? Thanks

like image 372
apurva Avatar asked Jun 07 '11 07:06

apurva


People also ask

What is dynamic table in HTML?

HTML Table. First a dynamic HTML Table is created using JavaScript createElement method. Adding the Header Row. The Header Row will be built using the first element of the Array as it contains the Header column text values.


1 Answers

Don't parse the HTML yourself, there are parsing libraries out there that can do that for you. Coupled with the HTML Agility Pack and LINQ, you can make short work of this.

var doc = new HtmlDocument();
doc.Load(url);

var nodes = doc.DocumentNode.SelectNodes("//table/tr");
var table = new DataTable("MyTable");

var headers = nodes[0]
    .Elements("th")
    .Select(th => th.InnerText.Trim());
foreach (var header in headers)
{
    table.Columns.Add(header);
}

var rows = nodes.Skip(1).Select(tr => tr
    .Elements("td")
    .Select(td => td.InnerText.Trim())
    .ToArray());
foreach (var row in rows)
{
    table.Rows.Add(row);
}
like image 132
Jeff Mercado Avatar answered Sep 28 '22 00:09

Jeff Mercado