Edit specific Element in XDocument Edit specific Element in XDocument xml xml

Edit specific Element in XDocument


With using System.Xml.Linq; it becomes

 var doc = XElement.Load(fileName); var saveGame = doc      .Element("savegames")      .Elements("savegame")      .Where(e => e.Element("IdNumber").Value == "2")      .Single(); saveGame.Element("balance").Value = "50"; doc.Save(fileName);


I think that the most compact way of doing it is using XDocument (System.Xml.Linq) and XPath extensions (System.Xml.XPath):

var xdoc = XDocument.Load(file);xdoc.XPathSelectElement("//savegame/IdNumber[text()='2']/../balance").Value = "50";xdoc.Save(file);

Once you learn XPath you never really want to go back to enumerating nodes manually.

EDIT: what does the query mean:

//savegame/IdNumber[text()='2']/../balance"  |        |                    |  ^ balance element ...  |        |                    ^ ... of parent ...  |        ^ ... of IdNumber element with inner value '2' ...  ^ ... of any savegame element in the doc

You can find XPath help here, and the updated link here.


   UpdateGameAttr(id ,  bal);   private void UpdateGameAttr(int id, int bal)   {       XDocument gmaes = XDocument.Load(@"D:\xxx\xxx\Game.xml");                   XElement upd = (from games in games.Descendants("savegame")                      where games.Element("IdNumber").Value == id.ToString()                      select games).Single();       upd.Element("balance").Value = bal.ToString();       gmaes.Save(@"D:\xxxx\xxx\Game.xml");   }