Search code examples
c#xmltagsupdating

Updating Value of XML Tag in C#


I am using a XML file as the main configuration (config.xml) source in my C# project, and therefore I need to be able to read data from and write data to this file. Included is the beginning of my XML which contains the tag I would like to update from within the app.

<?xml version="1.0" encoding="utf-8"?>
<root>
    <startupparams>
        <backColor>white</backColor>``` < -- Tag to update
        ``` <foreColor>black</foreColor>
    </startupparams>
    <strings>
        <appTitle>TheCalc</appTitle>
        <appAuthor>Matthew Croft</appAuthor>
        <appGreeting>Welcome</appGreeting>

The problem is that I am not too familiar with C# and XML integration, and writing (or more accurately updating) the tags to the file is the process that is causing me issue as I am not able to successfully do it. What I tried is included below.

Console.Write("Background Color: ");
string background = Console.ReadLine()!;
Console.WriteLine(background);
Console.WriteLine();
Console.Write("Foreground Color: ");
string foreground = Console.ReadLine()!;
XmlNodeList backColors = config.GetElementsByTagName("backColor");
for (int i = 0; i < backColors.Count; i++)
{
    backColors[i].InnerText = background;
}

Keep in mind that I have already opened the XML by using the following.

XmlDocument config = new XmlDocument();
string configFilePath = @"C:\Users\mcroftdev\Documents\TheCalc\config.xml";
config.Load(configFilePath);

Any suggestions you can provide would be greatly appreciated. Thank you in advance!


Solution

  • The commenting in your xml made it invalid. But you may have done that just for documentation in your post. For testing I created this file in Notepad++. Notepad++ can tell you if your XML file contains errors:

    xml

    This is the code I used. The primary change was to add a Save at the end. With a proper XML file and adding the Save the code works as intended.

    XmlDocument config = new XmlDocument();
    string configFilePath = @"d:\test.xml";
    config.Load(configFilePath);
    XmlNodeList backColors = config.GetElementsByTagName("backColor");
    for (int i = 0; i < backColors.Count; i++)
    {
      backColors[i].InnerText = "new background";
    }
    config.Save(configFilePath);