Accounting for specific child nodes with HtmlAgilityPack
I am having a lot of problems with this XPath release that I am using in HtmlAgilityPack.
I want to highlight all li
elements (if they exist) nested within another tag li
with tag a
with id="menuItem2"
. This is the html sample:
<div id="menu">
<ul>
<li><a id="menuItem1"></a></li>
<li><a id="menuItem2"></a>
<ul>
<li><a id="menuSubItem1"></a></li>
<li><a id="menuSubItem2"></a></li>
</ul>
</li>
<li><a id="menuItem3"></a></li>
</ul>
</div>
this is the XPath i used. When I lose this part /ul/li
, it gets the tag a
I wanted, but I need its descendants ... This XPath always returns null.
string xpathExp = "//a[@id='" + parentIdHtml + "']/ul/li";
HtmlNodeCollection liNodes = htmlDoc.DocumentNode.SelectNodes(xpathExp);
+2
source to share
4 answers
XPath is so messy. You are using HtmlAgilityPack, you can use LINQ as well.
//find the li -- a *little* complicated with nested Where clauses, but clear enough.
HtmlNode li = htmlDoc.DocumentNode.Descendants("li").Where(n => n.ChildNodes.Where(a => a.Name.Equals("a") && a.Id.Equals("menuItem2", StringComparison.InvariantCultureIgnoreCase)).Count() > 0).FirstOrDefault();
IEnumerable<HtmlNode> liNodes = null;
if (li != null)
{
//Node found, get all the descendent <li>
liNodes = li.Descendants("li");
}
0
source to share