HTML 敏捷包第一个特定的子节点

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>

所以我想访问 body-tag 的某些第一个子节点。在这种情况下,我只想要 p-tag 和 a-tag。

当前代码:

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

显然这不起作用,因为我只从 body-tag 中获取 p-tags。然而,是否有一些很棒的 xpath 代码也可以让我获得 a-tags。

您可以在 xpath 中使用 "or" (|)。所以你会看起来像这样:

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