2012-11-05 80 views
6

我想選擇除腳本節點和具有名爲'relativeNav'的類的ul節點。有人可以指引我走向正確的道路嗎?我一直在尋找這一個星期,我無法在任何地方找到它。目前我有這個,但它顯然選擇// ul [@ class ='relativeNav']。無論如何要放一個NOT表達式來讓SelectNode忽略那個呢?HtmlAgilityPack SelectNodes表達式忽略具有特定屬性的元素

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

回答

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> 

以下XPath表達式將選擇哪些不是所有節點腳本元素排除具有類'relativeNav'的UL元素的所有孩子:

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

更新:忘了提,如果你需要排除UL [CLASS =「relativeNav」]的任何兒童,不論其深度,你應該使用:

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

如果你想排除UI元素,以及(在上面,因爲該元素不包含文本的例子有點無關緊要的),你應該指定:

"//body//*[not(ancestor-or-self::ul[@class='relativeNav']) and not(self::script)]" 
+0

您的回答正是我一直在尋找的。感謝您對XPath的闡述。 – thaky

2

我希望這是你所需要的:

HtmlDocument doc = new HtmlDocument(); 
var nodesToExclude1 = doc.DocumentNode.SelectNodes("//ul[@class='relativeNav']"); 
var nodesToExclude2 = doc.DocumentNode.SelectNodes("//body//script"); 
var requiredNodes = doc.DocumentNode.SelectNodes("//") 
         .Where(node => !nodesToExclude1.Contains(node) && 
             !nodesToExclude2.Contains(node)); 

foreach (HtmlNode node in requiredNodes) 
{ 
    Console.WriteLine("Node: " + node); 
    singleString += node.InnerText.Trim() + "\n"; 
} 
+0

它給了一個「XPathException的:表達式的值必須爲節點集」當我用這種「變種requiredNodes =文檔。 DocumentNode.SelectNodes(「//」)。Where(node =>!nodesToExclude.Contains(node));「。另外我還有其他兩個要求,只選擇「// body」,而不是選擇腳本「// * [not(self :: script)]/text()」。當我將它們放在requiredNodes的SelectNodes下時,它給了我一個空對象異常。 「var requiredNodes = doc.DocumentNode.SelectNodes(」// body // * [not(self :: script)]/text()「)。 – thaky

+0

看到我編輯的答案。 –

+0

謝謝。 Linq表達將在未來適合我。 – thaky

相關問題