Search code examples
c#xmlinnertext

How do I edit Node Values in an Xml File with C#


I am trying to change the values in a Farming simulator 22 savegame xml file from C# in visual studio. There are a lot of nodes so I have reduced them to make things easier. I want to know how to replace the value in the node using C# with out having to create and rebuild the xml file from scratch.

the path to the xml file is: (C:\Users\Name\Documents\My Games\FarmingSimulator2022\savegame1\careerSavegame.xml)

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<careerSavegame revision="2" valid="true">
  <settings>
    <savegameName>My game save</savegameName>
    <creationDate>2022-05-03</creationDate>
    <mapId>MapFR</mapId>
    <mapTitle>Haut-Beyleron</mapTitle>
    <saveDateFormatted>2022-08-22</saveDateFormatted>
    <saveDate>2022-08-22</saveDate>
    <resetVehicles>false</resetVehicles>
</careerSavegame>

Solution

  • Through some research I found the solution to editing the values within the nodes. In this example I only change the value of savegameName, but it will be the same for the rest.

        //Routing the xml file 
        XmlDocument xmlsettings = new XmlDocument();
        xmlsettings.Load(@"D:\careerSavegame.xml");
    
        //Setting values to nodes through innertext
        String FarmNameSetting = "Martek Farm";
        XmlNode savegameNamenode = 
        xmlsettings.SelectSingleNode
        ("careerSavegame/settings/savegameName");
        savegameNamenode.InnerText = FarmNameSetting;