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

   }

here's a simple way to do this:

     XmlDocument doc = new XmlDocument();
     doc.Load(@"d:\tmp.xml");
     XmlNode node = doc["Data"]["savegames"];

     foreach (XmlNode childNode in node.ChildNodes)
     {
        if (childNode["IdNumber"].InnerText.Equals("1"))
        {
           childNode["balance"].InnerText = "88";
        }

     }
     doc.Save(@"d:\tmp.xml");

this code only change the balance of id "1"

it does it by going through the children of "savegames" and checking for each item the "IdNumber"