问题
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);
回答1:
The following XPath should work.
string xpathExp = "//li/a[@id='" + parentIdHtml + "']/following-sibling::ul/li";
回答2:
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.
回答3:
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");
}
回答4:
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
来源:https://stackoverflow.com/questions/10824623/count-specific-child-nodes-with-htmlagilitypack