How to select nested elements using HTML flexibility package?

I have the following xml / html view

<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 a collection of l1 tags, and for each l1 tag I want to select all the 'a' tags for the current l1 tag. how am i doing this

+6
c # html-agility-pack
source share
1 answer

HtmlAgilityPack uses the XPath selector to select nodes.

For your problem, this will 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"); } 

Please note that I used the XPath selector, which will capture all l1 elements in the document (using the leading // ), more specifically you can also do:

 var l1s = doc.DocumentNode.SelectNodes("root/p1/l1"); 
+6
source share

All Articles