开发者

How to select nested elements using HTML agility pack?

I have a following kind of xml/html

<root>
<p1>
    <l1>
        <a>something</a>
        开发者_C百科<a>something</a>
        <a>something</a>
        <a>something</a>
    </l1>
    <l1>
        <a>something</a>
        <a>something</a>
        <a>something</a>
        <a>something</a>
    </l1>
</p1>
</root>

I want to select collection of l1 tags and for each l1 tag i want to select all the 'a' tags for the current l1 tag. how do i do it??


HtmlAgilityPack uses XPath selectors to select nodes.

For your problem this would work:

HtmlDocument doc = new HtmlDocument();
doc.Load(@"test.html");

var l1s = doc.DocumentNode.SelectNodes("//l1");
foreach (var item in l1s)
{
    var links = item.SelectNodes("a");
}

Note that I used an XPath selector that will grab all l1 elements in the document (by using leading //), to be more specific you could also do:

var l1s = doc.DocumentNode.SelectNodes("root/p1/l1");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜