问题
I have the following code which should iterate through all the <td>
's in just one table (the fourth one on the page).
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table").Skip(4).Take(1))
{
Console.WriteLine(table.SelectNodes("//table").Count()); // = 5?
Console.WriteLine(table.SelectNodes("//table").Skip(4).Take(1).Count()); // = 1!
foreach (var td in table.SelectNodes("//td"))
{
Console.WriteLine(td.InnerText);
}
}
For some reason table.SelectNodes("//td")
is iterating through ALL five tables <td>
's.
Any ideas how I can correct this?
回答1:
You need to add single dot (.
) at the beginning of the XPath to make it recognized as relative path (in this case, relative to current table
) :
foreach (var td in table.SelectNodes(".//td"))
{
Console.WriteLine(td.InnerText);
}
来源:https://stackoverflow.com/questions/26176173/html-agility-pack-iteration-on-table-node-not-working