use*_*455 6 html c# datatable html-agility-pack
我想从HTML表格中导入一些数据(这里是链接http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html)并在我的表单应用程序中显示DataGridView中的前16个人.从我读到的最好的方法是使用HTML Agility包,所以我下载并包含在我的项目中.我知道首先要做的是加载html文件的内容.这是我过去常用的代码:
string htmlCode = "";
using (WebClient client = new WebClient())
{
client.Headers.Add(HttpRequestHeader.UserAgent, "AvoidError");
htmlCode = client.DownloadString("http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html");
}
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlCode);
Run Code Online (Sandbox Code Playgroud)
然后我卡住了.我不知道如何使用html表中的数据填充我的数据表.我尝试了很多不同的解决方案,但似乎没有什么工作正常.如果有人能帮助我,我会很高兴的.
Ser*_*kiy 14
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlCode);
var headers = doc.DocumentNode.SelectNodes("//tr/th");
DataTable table = new DataTable();
foreach (HtmlNode header in headers)
table.Columns.Add(header.InnerText); // create columns from th
// select rows with td elements
foreach (var row in doc.DocumentNode.SelectNodes("//tr[td]"))
table.Rows.Add(row.SelectNodes("td").Select(td => td.InnerText).ToArray());
Run Code Online (Sandbox Code Playgroud)
您需要HTML Agility Pack库才能使用此代码.