将HTML表转换为数据表的最佳方法是什么 [英] What is the best way of converting a Html table to datatable

查看:54
本文介绍了将HTML表转换为数据表的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html表.我想将其转换为数据表.最好的方法是什么?谢谢

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

推荐答案

不要自己解析HTML,那里有解析库可以为您做到这一点.与 HTML Agility Pack 和LINQ结合使用,您可以简化此工作.

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

这篇关于将HTML表转换为数据表的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆