开发者

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

I have a开发者_高级运维 html table.I want to convert this into a datatable. What is the best way of doing so? Thanks


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);
}


...some years later...

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

line has a typo and needs to be with double forward slash after 'table' and everything works like a charm

var nodes = doc.DocumentNode.SelectNodes("//table//tr");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜