2015-03-25 102 views
0

我試圖用HtmlAgilityPack刪除空的html節點。我想刪除所有節點是這樣的:如何用HtmlAgilityPack刪除空html節點?

<p><span>&nbsp;</span></p> 

這裏就是我想,但它不工作:你可以這樣做

static string RemoveEmptyParagraphs(string html) 
    { 
     HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); 
     document.LoadHtml(html); 
     foreach (HtmlNode eachNode in document.DocumentNode.SelectNodes("//p/span/text() = '&nbsp;'")) 
      eachNode.Remove(); 
     html = document.DocumentNode.OuterHtml; 
     return html; 
    } 
+0

兩件事。首先,如果你想刪除任何節點,你不能使用'foreach',而是使用'for'循環,因爲這是從列表中刪除項目的唯一正確方法。其次,嘗試將XPath字符串改爲'「// p/span [text()=' ']」'或'「// p/span [contains(text()=' ')]''if you期望任何空格在源HTML中出現。 – LightBulb 2015-03-25 10:56:16

+0

感謝LightBulb,我的xpath是一團糟,糾正了xpath。 – bearaman 2015-03-25 15:20:36

回答

0

之前document.LoadHtml(html);加載HTML:

document.LoadHtml(html.Replace("<p><span>&nbsp;</span></p>", "")); 

或者看看this

static void RemoveEmptyNodes(HtmlNode containerNode) 
{ 
    if (containerNode.Attributes.Count == 0 && !_notToRemove.Contains(containerNode.Name) && (containerNode.InnerText == null || containerNode.InnerText == string.Empty)) 
    { 
    containerNode.Remove(); 
    } 
    else 
    { 
    for (int i = containerNode.ChildNodes.Count - 1; i >= 0; i--) 
    { 
     RemoveEmptyNodes(containerNode.ChildNodes[i]); 
    } 
    } 
} 
+0

謝謝阿薩。最後,我使用了一個簡單的html.Replace,並做了這個訣竅。 – bearaman 2015-03-25 15:21:47

+0

@bearaman不客氣!很高興幫助:)! – Sid 2015-03-25 15:25:35