C# htmlAgilityPack将表解析为数据表或数组
我有这些桌子:C# htmlAgilityPack将表解析为数据表或数组,c#,linq,html-agility-pack,C#,Linq,Html Agility Pack,我有这些桌子: <table> <tbody> <tr><th>Header 1</th></tr> </tbody> </table> <table> <tbody> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 3</th> <
<table>
<tbody>
<tr><th>Header 1</th></tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
<th>Header 5</th>
</tr>
<tr>
<td>text 1</td>
<td>text 2</td>
<td>text 3</td>
<td>text 4</td>
<td>text 5</td>
</tr>
</tbody>
</table>
标题1
标题1
标题2
标题3
标题4
标题5
文本1
文本2
文本3
文本4
文本5
我正在尝试使用以下代码转换为数组或列表:
var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
from row in table.SelectNodes("tr").Cast<HtmlNode>()
from header in row.SelectNodes("th").Cast<HtmlNode>()
from cell in row.SelectNodes("td").Cast<HtmlNode>()
select new {
Table = table.Id,
Row = row.InnerText,
Header = header.InnerText,
CellText = cell.InnerText
};
var query=来自doc.DocumentNode.SelectNodes(“//表”).Cast()中的表
从表中的行中选择节点(“tr”).Cast()
从第行的标题中选择节点(“th”).Cast()
从第行的单元格中选择节点(“td”).Cast()
选择新{
Table=Table.Id,
Row=Row.InnerText,
Header=Header.InnerText,
CellText=cell.InnerText
};
但它不起作用。怎么了?一些注意事项:
- 你不需要石膏
- 假设每一行都有标题
- SelectNodes需要接收xpath,而您只传递名称
var query = from table in doc.DocumentNode.SelectNodes("//table")
where table.Descendants("tr").Count() > 1 //make sure there are rows other than header row
from row in table.SelectNodes(".//tr[position()>1]") //skip the header row
from cell in row.SelectNodes("./td")
from header in table.SelectNodes(".//tr[1]/th") //select the header row cells which is the first tr
select new
{
Table = table.Id,
Row = row.InnerText,
Header = header.InnerText,
CellText = cell.InnerText
};
为什么错了?显示异常或迄今为止获得的结果。结果视图返回:{“值不能为null\r\n名称生成参数:。源”}如何最好地将数据从此站点中分离?