2015-11-19 126 views
0

在HtmlAgilityPach,當我選擇這樣一個節點:如何選擇當前子節點中的所有標籤「a」?

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

我想所有的孩子在它的孩子「一」的標籤。然而,這並不工作,因爲它返回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 
} 

正如你所看到的,最後的方法選擇整個網頁,不僅當前childItem內的那些上的所有「A」標記(!)。我想知道爲什麼以及如何使它僅在「childNode」中選擇?

+0

嘗試childItem.DocumentNode.SelectNodes( 「// A [@href]」 ); –

回答

1

你只需要添加在的XPath的開始點(.),使其相對於當前childItem

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

但不「childItem」使它相對?爲什麼不? –

+0

不一定。當XPath以'/開始時,上下文將是根元素,忽略你正在執行XPath的任何元素 – har07

相關問題