Linq To XML - Can’t Remove Node
I have the following list
<Inventory>
<Car ID="1000">
<PetName>Jimbo</PetName>
<Color>Red</Color>
<Make>Ford</Make>
</Car>
<Car ID="1001">
<PetName>Jimbo</PetName>
<Color>Red</Color>
<Make>Ford</Make>
</Car>
</Inventory>
I am trying to remove the Car
node with ID = 1000, but i can't get it right
Here is my Code, note that the debugger never hits e.Remove
:
Dim doc As XDocument = XDocument.Load("Test.xml")
Dim e As XEle开发者_高级运维ment = From element
In doc.Elements("Inventory").Elements("Car")
Where element.Attribute("ID").Value = "1000"
Select element
e.Remove()
Your LINQ query returns an IEnumerable<XElement>
, not a single XElement
. Try this instead:
Dim e = From element
In doc.Root.Elements("Car")
Where element.Attribute("ID").Value = "1000"
Select element
e.Remove()
If that doesn't work make sure you have Option Infer
enabled to use implicitly typed variables or change the initialization to Dim e As IEnumerable(Of XEelement) = ...
to be explicit.
Since you're using an XDocument
you can use the Root
property instead of looking for the Inventory
node, i.e., doc.Root...
instead of doc.Elements("Inventory")...
.
精彩评论