Search code examples
filternodeshtml-agility-packchild-nodes

HTML agility pack first specific childnodes


<html>
<body>
    <p> This 
        <p> should not be displayed twice</p>
    </p>
    <a href="http://www.w3schools.com">Visit W3Schools.com!</a> 
    <div> Do not enter</div>
    <p> Gibberish </p>
</body>
</html>

So I want to access certain first child nodes of the body-tag. In this case I only want p-tag and a-tag.

Current code:

foreach(HtmlNode h in body.Elements("p"))
{
    if (h.Name == "p"){
        //Do something
    }
    if (h.Name == "a"){
       //Do something else
    }
}

Obviously this doesn't work since I only get the p-tags from the body-tag. However is there some awesome xpath code that can get me the a-tags aswell.


Solution

  • You can use an "or" (|) in your xpath. So you'd come out looking something like this:

    String xPath = "p|a";
    HtmlNodeCollection bodyDecendants = bodyNode.SelectNodes(xPath);