【问题标题】:How to select all the tags "a" in the current child node?如何选择当前子节点中的所有标签“a”?
【发布时间】:2015-11-19 13:21:55
【问题描述】:

在 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”中的那些?

【问题讨论】:

  • 试试 childItem.DocumentNode.SelectNodes("//a[@href]");

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


【解决方案1】:

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

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

【讨论】:

  • 但是“childItem”不是相对的吗?为什么不呢?
  • 不一定。当 XPath 以 / 开头时,上下文将是根元素,忽略您正在执行 XPath 的任何元素
猜你喜欢
  • 2015-06-06
  • 1970-01-01
  • 2012-08-21
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多