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

.net c# html html-agility-pack xpath

Question

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?

Accepted Answer

Use

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.


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.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why