2012-08-24 61 views
7

在我的代碼中,我想刪除沒有src值的img標籤。 我正在使用HTMLAgilitypack的HtmlDocument對象。 我找到img,它沒有src值,並試圖刪除它..但它給了我錯誤集合被修改;枚舉操作可能不會執行。 任何人都可以幫助我嗎? 我所使用的代碼是:從htmldocument刪除html節點:HTMLAgilityPack

foreach (HtmlNode node in doc.DocumentNode.DescendantNodes()) 
{ 
    if (node.Name.ToLower() == "img") 
    {        
      string src = node.Attributes["src"].Value; 
      if (string.IsNullOrEmpty(src)) 
      { 
       node.ParentNode.RemoveChild(node, false);  
      } 
    } 
    else 
    { 
      ..........// i am performing other operations on document 
    } 
} 

回答

6

我所做的是:

List<string> xpaths = new List<string>(); 
    foreach (HtmlNode node in doc.DocumentNode.DescendantNodes()) 
    { 
         if (node.Name.ToLower() == "img") 
         { 
          string src = node.Attributes["src"].Value; 
          if (string.IsNullOrEmpty(src)) 
          { 
           xpaths.Add(node.XPath); 
           continue; 
          } 
         } 
    } 

    foreach (string xpath in xpaths) 
    { 
      doc.DocumentNode.SelectSingleNode(xpath).Remove(); 
    } 
17

看來您使用了HtmlNode.RemoveChild方法枚舉過程中修改集合。

要解決此問題,您需要將您的節點複製到單獨的列表/數組中,方法是調用Enumerable.ToList<T>()Enumerable.ToArray<T>()

var nodesToRemove = doc.DocumentNode 
    .SelectNodes("//img[not(string-length(normalize-space(@src)))]") 
    .ToList(); 

foreach (var node in nodesToRemove) 
    node.Remove(); 

如果我是對的,問題就會消失。

+0

感謝,這對我的作品..! – Priya

+0

@Piya,很高興聽到這個消息。但我認爲通過使用一個xpath表達式更容易使代碼更具可讀性(只需選擇要使用一個表達式刪除的所有節點)。 – Alex

+0

,是的你說得對。可以,我會做的..再次感謝! – Priya

2
var emptyImages = doc.DocumentNode 
.Descendants("img") 
.Where(x => x.Attributes["src"] == null || x.Attributes["src"].Value == String.Empty) 
.Select(x => x.XPath) 
.ToList(); 

emptyImages.ForEach(xpath => { 
     var node = doc.DocumentNode.SelectSingleNode(xpath); 
     if (node != null) { node.Remove(); } 
    });