Selecting the current element in a loop using Html Agility Pack (XPATH)

.net c# html html-agility-pack xpath


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</a>
<div class="itembox">
    <a Class="head" href="">Two</a>
<!-- 10 itembox elements-->

Is my XPath expression wrong? am i missing something?

1/15/2012 6:19:42 PM

Accepted Answer


var test = e.SelectNodes(".//a[@class='head']");

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:

var test = e.SelectNodes("a[@class='head']");

As always see the Xpath spec for details.

1/15/2012 5:56:00 PM

Popular Answer

 var test = e.SelectNodes("//a[@class='head']");

This is an absolute expression, but you need a relative XPath expression -- to be evaluated off e.

Therefore use:

 var test = e.SelectNodes("a[@class='head']");

Do note: Avoid using the XPath // pseudo-operator as much as possible, because such use may result in significant inefficiencies (slowdown).

In this particular XML document the a elements are just children of div -- not at undefinite depth off div.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow