开发者

Linq To XML - Can’t Remove Node

开发者 https://www.devze.com 2023-04-02 08:21 出处:网络
I have the following list <Inventory> <Car ID=\"1000\"> <PetName>Jimbo</PetName>

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")....

0

精彩评论

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

关注公众号