This project has moved and is read-only. For the latest updates, please go here.

Collection was modified error when removing nodes in v1.4

Topics: Developer Forum, User Forum
Apr 4, 2012 at 6:04 PM

I'm using a modified version of the ConvertTo method found in HtmlConvert.cs (Html2Txt project that comes with HAP source code) to iterate through the entire HtmlDocument's DocumentNode and manipulate the node tree (for ex. by removing certain nodes). The problem is that ConvertTo method processes child nodes in a recursive fashion:

private void ConvertContentTo(HtmlNode node, TextWriter outText)
      foreach (HtmlNode subnode in node.ChildNodes)
            ConvertTo(subnode, outText);

In the old 1.3 version of HAP, this code would work fine when I would remove nodes in ConvertTo method; however, the new version 1.4 throws an error:

"Collection was modified; enumeration operation may not execute"

because node.ChildNodes collection has been modified inside ConvertTo (when I removed nodes from it). Any ideas on how to deal with this?


Apr 5, 2012 at 3:00 AM

Fixed with this code:

private void ConvertContentTo(HtmlNode node)
      int i = 0;
      int childNodeCount = node.ChildNodes.Count;
      while (i < childNodeCount)
           childNodeCount = node.ChildNodes.Count;