Nodes selection inside HtmlNodeCollection with HTML Agility Pack

c# html-agility-pack linq xmlnode xml-parsing

Question

I have html structure like that:

<div class="class1">
    <div class="class2">
        <a href="test" title="professional and enthusiast programmers">Stack Overflow</a>
    </div>
    <div class="class2">
    </div>
    <div class="class2">
    </div>
    <div class="class2">
    </div>
</div>
<div class="class1">
    <div class="class2">
        <a href="test" title="professional and enthusiast programmers">Stack Overflow</a>
    </div>
</div>

I am trying to select all nodes with class1:

HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//*[contains(@class,' class1 ')]");

And select all nodes inside that node which contains class2:

foreach (HtmlNode node in nodes)
{
   HtmlNodeCollection nodes2 = node.SelectNodes("//*[contains(@class,' class2 ')]");
}

But nodes2 gets class2 from all nodes. What am I doing wrong?

1
3
1/10/2018 6:00:26 PM

Accepted Answer

var nodes = doc.DocumentNode.SelectNodes("//div[@class='class1']");

var nodes2 = nodes.Select(c1 => c1.SelectNodes("div[@class='class2']"));
4
2/19/2014 7:29:05 PM

Popular Answer

Alternative XPath worked for me

var nodes = doc.DocumentNode.SelectNodes("//div[@class='class1']");
var nodes2 = nodes.Select(c1 => c1.SelectNodes(".//div[@class='class2']"));


Related Questions





Related

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