HTML Agility Pack - Get div without class or id (C#)

c# html-agility-pack parsing

Question

I've been trying to follow some solutions here on StackOverflow but I need some help.
This is the source HTML:

<div class="myclass">
 <div style="font-size:2em;"> STRING_N1 </div>
 <div> STRING_N2 </div>
</div>

And this is my current code:

        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(htmlcode);
        var res = doc.DocumentNode.SelectNodes("//div[@class='myclass']");
        foreach (var item in res)
        {
            var firstDiv = item.SelectSingleNode("div");
            var content1 = firstDiv.ChildNodes[0].InnerText.Trim();
            richTextBox1.AppendText(content1.ToString());
        }

So far so good, I can extract "STRING_N1" without a problem. However, I can't figure it out on how to extract STRING_N2 without having a class or id.
Thank you.

Accepted Answer

You can use LINQ to get descendant divs:

var divs = doc.DocumentNode.SelectNodes("//div[@class='myclass']") 
              .SelectMany(x => x.Descendants("div"));

var contents = divs.Select(x => x.InnerText.Trim());

richTextBox1.AppendText(string.Join(Environment.NewLine, contents);



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