A.Gecu A.Gecu - 15 days ago 12
C# Question

How to update xml file in c#

the XML file that i have

<Account>
<account>
<userid>4</userid>
<iban>TR600061200000012990025478</iban>
<accountno>0000012990025478</accountno>
<money>
</money>
<identityno>78546985462</identityno>
<birthdate>28.05.1986</birthdate>
<adress>İstanbul/Üsküdar</adress>
</account>
</Account>


when i click button_2 in c#, the value in textbox, will make money in xml to update.

the c# codes that i have

{
XDocument doc = XDocument.Load(@"XMLFile1.xml");
var node = doc.Descendants("Account").FirstOrDefault(personDetail => personDetail.Element("money").Value==txt.Text);
node.SetElementValue("money", this.txt.Text);
doc.Save(@"XMLFile1.xml");
}

Answer

Use XDocument to parse the xml string. Find the money XElement and update his value.

public void Button1_Click(object sender, EventArgs e)
{
    XDocument doc = XDocument.Load(@"XMLFile1.xml");

    var result = doc.Root.Descendants("money").FirstOrDefault();

    if (result == null)
       return;

    result.Value = txt.Text;
    doc.Save(@"XMLFile1.xml"); 

}

EDIT

Check dotNetFiddle