How can I use HTML agility pack to pick nested elements?

c# html-agility-pack

Question

I have a following kind of xml/html

<root>
<p1>
    <l1>
        <a>something</a>
        <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??

1
6
2/21/2011 4:25:42 PM

Accepted Answer

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");
7
2/21/2011 4:38:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow