2012-07-20 87 views
3

刪除所有空的和不必要的節點的首選方法是什麼?例如從HTML中刪除所有空白/不必要的節點

<p></p>應該被刪除,<font><p><span><br></span></p></font>也應刪除(所以BR標籤被認爲在這種情況下unneccesery)

我將不得不使用某種形式的遞歸函數的這個?我在想這個可能是:

RemoveEmptyNodes(HtmlNode containerNode) 
{ 
    var nodes = containerNode.DescendantsAndSelf().ToList(); 

     if (nodes != null) 
     { 
      foreach (HtmlNode node in nodes) 
      { 
       if (node.InnerText == null || node.InnerText == "") 
       { 
        RemoveEmptyNodes(node.ParentNode); 
        node.Remove(); 
       } 
      } 
     } 
    } 

但這顯然不起作用(stackoverflow例外)。不應該刪除您可以添加名稱到列表中,並與屬性節點

+1

有一個** 「空」和「不必要」之間的巨大差異。刪除空節點可能會損壞佈局。 – 2012-07-20 12:14:30

+0

好吧,所以我最好不要刪除空節點? – 2012-07-20 12:17:25

+0

可能不是,沒有。另一個原因:如果你真的打算將'img'元素視爲空白,我會感到驚訝。 – hvd 2012-07-20 12:20:23

回答

10

標籤也不會因爲containerNode.Attributes.Count == 0(例如圖像)的去除

static List<string> _notToRemove; 

static void Main(string[] args) 
{ 
    _notToRemove = new List<string>(); 
    _notToRemove.Add("br"); 

    HtmlDocument doc = new HtmlDocument(); 
    doc.LoadHtml("<html><head></head><body><p>test</p><br><font><p><span></span></p></font></body></html>"); 
    RemoveEmptyNodes(doc.DocumentNode); 
} 

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