I’m trying to remove individual nodes from their parent, I tried the Remove method but it doesn’t seem to be working. How is this done? Is this a bug or what?
Sub Main()
Dim xml =
<?xml version="1.0" encoding="utf-8"?>
<Products>
<Product name="ABC-1" link="http://www.site.com/1"/>
<Product name="ABC-2" link="http://www.site.com/2"/>
<Product name="ABC-3" link="http://www.site.com/3"/>
</Products>
Dim products = xml.Root.<Product>
'works - uncomment
'products.Remove()
'Doesn't work
For Each product In products
product.Remove()
Next
xml.Save(FailedFilename)
End Sub
Removing the nodes while looping over
productscauses it to be modified. Since it’s anIEnumerable<XElement>you need to avoid lazy evaluation in order to work on the entire result at once. To do so simply add a call toToArray()orToList():Note that the above is equivalent to the following snippet. It is not the same as adding
ToArray()while declaring theproductsvariable:The issue you’re running into is nicely summarized on this MSDN page: Mixed Declarative Code/Imperative Code Bugs, specifically the section titled “Deleting While Iterating.”
Unless you need to work with each
productprior to removing it, the first approach of using theRemoveextension method is much simpler:products.Remove().