Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# htmlAgilityPack将表解析为数据表或数组_C#_Linq_Html Agility Pack - Fatal编程技术网

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,而您只传递名称
如果我是你,我会使用foreach对我的数据进行建模,这样我可以获得更多的控制和效率,但如果你仍然想按自己的方式进行,这就是应该的方式

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名称生成参数:。源”}如何最好地将数据从此站点中分离?