pdf asker pdf asker - 1 year ago 173
C# Question

HTMLAgilityPack - Remove Node but retain its value

ive read in this site that this question is ask before. but i tried the code but its not working

all the answers are the same. using a single code

item.ParentNode.RemoveChild(item, true);

but i used that in my code but it doesnt work. i received an error

Collection was modified; enumeration operation may not execute.

this is my code as of now

string html = "<xml><span> some text </span><p><span> Hello</span> </p></xml>";
var htmlSpan = new HtmlDocument();
var rootSpan = htmlSpan.DocumentNode;
var anchorsSpan = rootSpan.Descendants("span");
foreach (var item in anchorsSpan)
item.ParentNode.RemoveChild(item, true);
catch (Exception ex)

what am i doing is removing the span tag but retain is text

so the output must be

<xml> some text <p> Hello </p></xml>

Answer Source


            foreach (var item in anchorsSpan.ToArray())
                item.ParentNode.RemoveChild(item, true);

The Descendants function returns a dynamic list of child elements that is built while traversing over it. So, it is not allowed to change the document while traversing over the dynamic list. The solution is to make a static copy of the list beforehand (using ToArray) and traverse over that array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download