Count specific child nodes with HtmlAgilityPack

萝らか妹 提交于 2019-12-04 15:47:25

The following XPath should work.

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

Try this for your xpath:

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

The problem is that you were select the a node itself, which has no ul children. You need to select the li node first, and filter on its a child.

XPath is so messy. You're using the HtmlAgilityPack, you might as well leverage the LINQ.

//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");
}

From your description I think you want to select the two <li> elements that contain <a> tags with ids menuSubItem1 and menuSubItem2?

If so then this is what you need

//li[a/@id="menuItem2"]//li
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!