Search code examples
c#anglesharp

How is it possible to remove all rows from the HTML table using anglesharp?


How is it possible to remove all rows from the HTML table using anglesharp?

I am trying to remove all rows in table. I've read this documentation, however, rows are not removed.

My code looks like this:

public void DeleteRows(IElement table)
{
    foreach (var row in table?.QuerySelectorAll("tr"))
    {
        row.Remove();
    }
    var lengthAfterDeletion = table?.QuerySelectorAll("tr")?.Length;
}

How is it possible to remove all rows from the HTML table using anglesharp?


Solution

  • I think we figured it out in the meantime (see https://github.com/AngleSharp/AngleSharp/issues/838).

    Just for future reference (in case somebody else runs into the same problem, which happens quite easily):

    public void DeleteRows(IElement table)
    {
        var rows = table?.QuerySelectorAll("tr").ToArray();
        foreach (var row in rows)
        {
            row.Remove();
        }
        var legnthAfterDeletion = table?.QuerySelectorAll("tr")?.Length;
    }
    

    The key is to get a static snapshot of the result before changing the DOM. Hence the .ToArray() which comes from LINQ and can be applied to any iterator.