如何选择当前子节点中的所有标签“a”?

时间:2015-11-19 04:58:28

标签: c# html parsing html-agility-pack

在HtmlAgilityPach中,当我选择这样一个节点时:

  var node1 = htmlDoc.GetElementbyId("some_id");

我想在孩子身上得到所有孩子的“a”标签。但是,这不起作用,因为它返回null:

foreach (var childItem in node1.ChildNodes) {
  var a = childItem.SelectNodes("a") // null
  var a = childItem.SelectNodes("/a") // null
  var a = childItem.SelectNodes("//a") // not null but select all the "a" tags on the whole(!) page, not only the ones within current childItem
}

如您所见,最后一个方法选择整个(!)页面上的所有“a”标记,而不仅仅是当前childItem中的标记。我想知道为什么以及如何让它只在“childNode”中选择那些?

1 个答案:

答案 0 :(得分:1)

您只需在XPath的开头添加一个点(.),使其相对于当前childItem

var a = childItem.SelectNodes(".//a");