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?

Accepted Answer

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

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



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