Search code examples
c#xmlsettingseditupdating

How to edit an Xml file's element values


I have this Xml file, and I want to edit any of the elements like homepage or search_provider.

<?xml version="1.0" encoding="utf-8"?>
    <Preferences>
      <personal>
        <homepage>http://duckduckgo.com</homepage>
        <search_provider>DuckDuckGo</search_provider>
        <search_provider_url>http://duckduckgo.com/?q=</search_provider_url>
      </personal>
    </Preferences>

The following is the C# code I'm using to attempt to change the homepage element. Let's say I run saveSetting("homepage", "http://google.com");

            public static void saveSetting(String settingName, String newvalue)
            {
               XmlDocument xml = new XmlDocument();

               xml.Load(userSettingsFile);

               foreach (XmlElement element in xml.SelectNodes("Preferences"))
               {
                   foreach (XmlElement oldsettingname in element)
                   {
                       element.SelectSingleNode(settingName);

                       XmlNode settingtosave = xml.CreateElement(settingName);

                       settingtosave.InnerText = newvalue;

                       element.ReplaceChild(settingtosave, oldsettingname);

                       xml.Save(userSettingsFile);
                   }
               }
            }

Now, while this works to an extent and does change the specified value, it also deletes the entire personal element.

<?xml version="1.0" encoding="utf-8"?>
<Preferences>
  <homepage>http://google.com</homepage>
</Preferences>

Hopefully someone can help me out! I've been searching for the last two days for a solution and this is the closest I've come to getting the code to work the way I need it to.


Solution

  • You can just use LINQ to XML like this:

    public static void saveSetting(String settingName, String newvalue)
    {
        var xmlDocument = XDocument.Load("path");
    
        var element = xmlDocument.Descendants(settingName).FirstOrDefault();
    
        if (element != null) element.Value = newvalue;
    
        xmlDocument.Save("path");
    }
    

    See this documentation for more details: Modifying Elements, Attributes, and Nodes in an XML Tree