pdf asker pdf asker - 22 days ago 9
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

try
{
string html = "<xml><span> some text </span><p><span> Hello</span> </p></xml>";
var htmlSpan = new HtmlDocument();
htmlSpan.LoadHtml(html);
var rootSpan = htmlSpan.DocumentNode;
var anchorsSpan = rootSpan.Descendants("span");
foreach (var item in anchorsSpan)
{
item.ParentNode.RemoveChild(item, true);
}
//htmlSpan.Save(fileName);
Console.WriteLine(htmlSpan.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}


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

Use

            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.