how to to get childs node with 'html agility pack'

c# html-agility-pack

Question

how to to get childs node with 'html agility pack' ?

var Webget = new HtmlWeb();
var doc = Webget.Load(url);
HtmlNode elementbyId = doc.GetElementbyId("nome");

I just need to take internal node in <div id="nome">

html :

<div id="nome">
    <p> <!-- this node --> 
    <strong></strong>
    </p>
    <br/><!-- this node --> 
    <span><!-- this node --> 
    <strong></strong>
    </span>
    <p><!-- this node --> 
    <span></span>
    </p>
</div>

update :

I wrote the following code, but it is wrong.

var nodes = elementbyId.Descendants();

this code Get all the elements inside <div id="nome">

Is there a way to solve the problem? I have no idea

Accepted Answer

Use SelectNodes("*") instead of Descendants() to get direct children elements of current element. Here is a working example :

var html = @"<div id='nome'>
    <p> <!-- this node --> 
    <strong></strong>
    </p>
    <br/><!-- this node --> 
    <span><!-- this node --> 
    <strong></strong>
    </span>
    <p><!-- this node --> 
    <span></span>
    </p>
</div>";
var doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNode elementbyId = doc.GetElementbyId("nome");
var nodes = elementbyId.SelectNodes("*");
foreach (var htmlNode in nodes)
{
    Console.WriteLine(htmlNode.OuterHtml);
    Console.WriteLine("-----------------------");
}

Dotnetfiddle Demo

output :

<p> <!-- this node -->
    <strong></strong>
    </p>
-----------------------
<br/>
-----------------------
<span><!-- this node -->
    <strong></strong>
    </span>
-----------------------
<p><!-- this node -->
    <span></span>
    </p>
-----------------------



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