Count specific child nodes with HtmlAgilityPack

c# html html-agility-pack xpath

Question

I have lot of trouble with this XPath selction that i use in HtmlAgilityPack.

I want to select all li elements (if they exist) nested in another li witch have a tag with id="menuItem2". This is 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 XPath that i been using. When i lose this part /ul/li, it gets me the a tag that I wanted, but i need his descendants... This XPath always returns null.

string xpathExp = "//a[@id='" + parentIdHtml + "']/ul/li";
HtmlNodeCollection liNodes = htmlDoc.DocumentNode.SelectNodes(xpathExp);

Popular Answer

The following XPath should work.

string xpathExp = "//li/a[@id='" + parentIdHtml + "']/following-sibling::ul/li";



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why