使用HtmlAgilityPack C#从html文档中获取特定的表



我有一个带有两个表的html文档。例如:

<html>
<body>
<p>This is where first table starts</p>
<table>
<tr>
<th>head</th>
<th>head1</th>
</tr>
<tr>
<td>data</td>
<td>data1</td>
</tr>
</table>
<p>This is where second table starts</p>
<table>
<tr>
<th>head</th>
<th>head1</th>
</tr>
<tr>
<td>data</td>
<td>data1</td>
</tr>
</table>
</body>
</html>

我想分别解析第一个和第二个我将解释:

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(@richTextBox1.Text);
if(comboBox_tables.Text.Equals("Table1"))
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("inserted_at", typeof(string));
dt.Columns.Add("DisplayName", typeof(string));
HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[1]");
foreach (var row in doc.DocumentNode.SelectNodes("//tr"))
{
var nodes = row.SelectNodes("td");
if (nodes != null)
{
var id = nodes[0].InnerText;
var inserted_at = nodes[1].InnerText;
var DisplayName = nodes[2].InnerText;
dt.Rows.Add(id, inserted_at, DisplayName);
}
dataGridView1.DataSource = dt;

我正在尝试用//表[1]选择第一个表。但它总是两全其美。如何为if(表1(选择第一个表,为else if(表2(选择第二个表?

您正在选择table[1],但没有对返回值执行任何操作。使用table变量可以选择所有tr节点。

HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[1]");
foreach (var row in table.SelectNodes("//tr"))

代码的其余部分

最新更新