Html Agility Pack, iteration on table node not working

时光总嘲笑我的痴心妄想 提交于 2019-12-12 04:49:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!