I’m trying to do something simple, but somehow it doesnt work for me, here’s my code:
var items = html.DocumentNode.SelectNodes("//div[@class='itembox']");
foreach(HtmlNode e in items)
{
int x = items.count; // equals 10
HtmlNode node = e;
var test = e.SelectNodes("//a[@class='head']");// I need this to return the
// anchor of the current itembox
// but instead it returns the
// anchor of each itembox element
int y =test.count; //also equals 10!! suppose to be only 1
}
my html page looks like this:
....
<div class="itembox">
<a Class="head" href="one.com">One</a>
</div>
<div class="itembox">
<a Class="head" href="two.com">Two</a>
</div>
<!-- 10 itembox elements-->
....
Is my XPath expression wrong? am i missing something?
Use
instead. Your current code (
//a[]) searches all a elements starting from the root node. If you prefix it with a dot instead (.//a[]) only the descendants of the current node will be considered. Since it is a direct child in your case you could of course also do:As always see the Xpath spec for details.