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


The following XPath should work.



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

      

+1


source


Try this for your xpath:

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

      



The problem is that you yourself have chosen a a

node that has no children ul

. First you need to select a li

node and filter its child a

.

0


source


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


From your description, I think you want to select two elements <li>

that contain tags <a>

with ids menuSubItem1

and menuSubItem2

?

If so, then this is what you need

//li[a/@id="menuItem2"]//li

      

0


source







All Articles