Linq to XML - update/alter the nodes of an XML Document

后端 未结 6 1682
旧巷少年郎
旧巷少年郎 2020-11-29 06:04

I\'ve got 2 Questions:

1. I\'ve sarted working around with Linq to XML and i\'m wondering if it is possible to change an XML document via Linq. I mean, is there some

6条回答
  •  甜味超标
    2020-11-29 06:30

    The answers are in this thread...you just have to do a lot of sorting to find them, so I've done the work of compliling them for you:

    1. YES you can edit elements
    2. Deleting elements is easy: element.Remove(); (Remember to save the xDocument after that)

    Now if you're reading this thread, you probably want to know HOW to edit elements. There are two different ways that data is stored in xml, e.g.:

    another value
    
    1. As an ATTRIBUTE on a tag
    2. As the content (read value) of the tag

    To edit the value of an attribute, knox answered his own question:

    d.Descendants("record").Where(x => x.Attribute("id").Value == "2").Single().SetAttributeValue("info", "new sample info");
    

    In other words, get the XElement that you want to alter, and call element.SetAttributeValue("AttributeName", "new value for the attribute")

    if you want to edit the value or contents of a tag, then Ajay answered it (if you dig through all his code):

    persondata.Element("City").Value = txtCity.Text;
    

    Or, in other words, once you have the XElement you're after, just use .Value and assign away.

    Remember that after you perform any of these modifications on the elements in memory, you've got to call .Save() on the XDocument if you want to persist those changes to disk.

提交回复
热议问题