Update XML with C# using Linq

To update your xml use SetElementValue method of the XElement :

var items = from item in xmlDoc.Descendants("item")
    where item.Element("itemID").Value == itemID
    select item;

foreach (XElement itemElement in items)
{
    itemElement.SetElementValue("name", "Lord of the Rings Figures");
}

EDIT : Yes, I tried your example and it saves updated data to the file. Save your updated xml with Save method of the XDocument, here is the code that I tried :

string xml = @"<items>
           <item>
            <itemID>1</itemID>
            <isGadget>True</isGadget>
            <name>Star Wars Figures</name>
            <text1>LukeSkywalker</text1>
           </item>
        </items>";

XDocument xmlDoc = XDocument.Parse(xml);

var items = from item in xmlDoc.Descendants("item")
            where item.Element("itemID").Value == "1"
            select item;

foreach (XElement itemElement in items)
{
    itemElement.SetElementValue("name", "Lord of the Rings Figures");
}

xmlDoc.Save("data.xml");

Leave a Comment