从htmldocument中删除html节点:HTMLAgilityPack

Pri*_*iya 10 c# iteration collections dom html-agility-pack

在我的代码中,我想删除没有src值的img标记.我正在使用HTMLAgilitypack的HtmlDocument对象.我发现img没有src值并试图删除它..但它给了我错误集合被修改; 枚举操作可能无法执行.任何人都可以帮助我吗?我使用的代码是:

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
   }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 23

看来你正在使用HtmlNode.RemoveChild方法在枚举期间修改集合.

要解决此问题,您需要通过调用eg 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();
Run Code Online (Sandbox Code Playgroud)

如果我是对的,问题就会消失.


Pri*_*iya 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();
    }
Run Code Online (Sandbox Code Playgroud)