Html Agility Pack get specific content inside a double div

.net c# html html-agility-pack

Question

I am new to HTML Agility pack and i haven't figured out how can i parse the following block of code:

<p>
    <div class='myclass1'>
        <div id='idXXXX'>content1<br>content2
        </div>  
        <div class="myclass2">
            <table>
                <tr>
                    <td align="left">content3 <b><a href="">content4</a></b></td>
                    <td align="right">content5 <b><a href="">content6</a></b></td>
                </tr>
            </table>
        </div>
    </div>
</p>

where XXXX is a random generated number.

I have all the code to load the HTML document.

What i want from the above code is to get content1 and content2 and in a different query content4.

Accepted Answer

var doc = new HtmlDocument();
doc.Load("test.htm");
var res = doc.DocumentNode.SelectSingleNode("//div[@class='myclass1']");
var firstDiv = res.SelectSingleNode("div");
var content1 = firstDiv.ChildNodes[0].InnerText.Trim();
var content2 = firstDiv.ChildNodes[2].InnerText.Trim();
var content4 = res.SelectSingleNode(".//div[@class='myclass2']")
                  .SelectSingleNode(".//td[@align='left']/b/a")
                  .InnerText
                  .Trim();

UPDATE:

If you have multiple divs with the given classes and you want to match the content for each of them you could do this:

var doc = new HtmlDocument();
doc.Load("test.htm");
var res = doc.DocumentNode.SelectNodes("//div[@class='myclass1']");
foreach (var item in res)
{
    var firstDiv = item.SelectSingleNode("div");
    var content1 = firstDiv.ChildNodes[0].InnerText.Trim();
    var content2 = firstDiv.ChildNodes[2].InnerText.Trim();
    var content4 = item.SelectSingleNode(".//div[@class='myclass2']")
                       .SelectSingleNode(".//td[@align='left']/b/a")
                       .InnerText
                       .Trim();
}


Related

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