C# 使用HtmlAlityPack获取不同的元素表
我多次使用这种循环结构。 表1 表2C# 使用HtmlAlityPack获取不同的元素表,c#,html-agility-pack,C#,Html Agility Pack,我多次使用这种循环结构。 表1 表2 <table> <tbody> <tr> <th>Texto</th> <th>Texto</th> <th>Texto</th> <th>Texto</th> </tr>
<table>
<tbody>
<tr>
<th>Texto</th>
<th>Texto</th>
<th>Texto</th>
<th>Texto</th>
</tr>
</tbody>
</table>
这种模式重复了好几次。
如何将它们切换到数组和列表中以获取值每个?使用控制台应用程序的简短演示:
class Program
{
static void Main(string[] args)
{
HtmlDocument doc = new HtmlDocument();
doc.Load("Demo.html");
var result = doc.DocumentNode.SelectNodes("//table")
.Select(table => new //create anonymous type
{
Table = table,
HeaderNodes = table.SelectNodes("./tbody/tr/th").ToList() //the th subnodes
});
foreach (var table in result)
{
foreach (HtmlNode headerNode in table.HeaderNodes)
{
Console.WriteLine( headerNode.InnerText);
}
Console.WriteLine("--------------------------");
}
}
}
输出:
titulo
--------------------------
Texto
Texto
Texto
Texto
--------------------------
Alternative HeaderNodes=table.SelectNodes//th.ToList如果需要一个表数组,只需在选择器之后调用.ToArray创建您自己的类型并执行。Selecttable=>new Yourtype{…}.ToArray;
titulo
--------------------------
Texto
Texto
Texto
Texto
--------------------------