开发者

XElement.Remove (XNode.Remove) doesn't work

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 produc开发者_开发问答t In products
    product.Remove()
  Next

  xml.Save(FailedFilename)
End Sub


Removing the nodes while looping over products causes it to be modified. Since it's an IEnumerable<XElement> you need to avoid lazy evaluation in order to work on the entire result at once. To do so simply add a call to ToArray() or ToList():

For Each product In products.ToArray()
    product.Remove()
Next

Note that the above is equivalent to the following snippet. It is not the same as adding ToArray() while declaring the products variable:

Dim temp = products.ToArray()
For Each product In temp
    product.Remove()
Next

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 product prior to removing it, the first approach of using the Remove extension method is much simpler: products.Remove().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜