HtmlAgilityPack SelectNodes表达式忽略具有特定属性的元素

tha*_*aky 6 c# xpath selectnodes html-agility-pack

我试图选择除脚本节点以外的节点和一个名为'relativeNav'的类的ul.有人可以指引我走正确的道路吗?我已经搜索了一个星期,我无法在任何地方找到它.目前我有这个,但它显然也选择了// ul [@ class ='relativeNav'].反正是否有一个NOT表达式,以便SelectNode会忽略那个?

        foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//body//*[not(self::script)]/text()"))
        {
            Console.WriteLine("Node: " + node);
            singleString += node.InnerText.Trim() + "\n";
        }
Run Code Online (Sandbox Code Playgroud)

Ant*_*ill 4

给定一个结构类似于以下内容的 Html 文档:

<html>
<head><title>HtmlDocument</title>
</head>
<body>
<div>
<span>Hello Span World</span>
<script>
Script Text
</script>
</div>
<ul class='relativeNav'>
<li>Hello </li>
<li>Li</li>
<li>World</li>
</ul>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

以下 XPath 表达式将选择所有不是脚本元素的节点,不包括具有“relativeNav”类的 UL 元素的所有子节点:

var nodes = htmlDoc.DocumentNode.SelectNodes("//body//*[not(parent::ul[@class='relativeNav']) and not(self::script)]/text()");
Run Code Online (Sandbox Code Playgroud)

更新:忘记提及,如果您需要排除 ul[class='relativeNav'] 的任何子级,无论其深度如何,您应该使用:

"//body//*[not(ancestor::ul[@class='relativeNav']) and not(self::script)]/text()"
Run Code Online (Sandbox Code Playgroud)

如果您还想排除 ul 元素(在上面的示例中有些不相关,因为该元素不包含文本),您应该指定:

"//body//*[not(ancestor-or-self::ul[@class='relativeNav']) and not(self::script)]"
Run Code Online (Sandbox Code Playgroud)