开发者

Html Agility Pack get specific content inside a double div

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.


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜