Matthias Weiß Matthias Weiß - 1 month ago 4x
C# Question

Edit specific Element in XDocument

I recently started learning C# and I ran into a problem using

to store data. I hope the question is understandable as I am not familiar with all the correct terms yet and as English isn't my first language.

I read a lot of Questions/googled but I can not figure it out myself.

I want to update an existing XDocument File that looks like this:


What is the easiest way to change a value in a specific Element?

Let's say I want to change the balance of a specific savegame.

I want to access the savegame by IdNumber (these numbers are unique)

Then I want to change the value of balance (for example to 50) and then save these changes to my document.


With using System.Xml.Linq; it becomes

 var doc = XElement.Load(fileName);
 var target = doc
      .Where(e => e.Element("IdNumber").Value == "2")

 target.Element("balance").Value = "50";