How can I change an attribute value of a XML file

2020-07-24 04:32发布

问题:

I have a XML file(web.config) and I need to edit the value attribute of each tag, depend of the key name...

this is an example of the XML file:

<appSettings>
  <add key="A1" value="Hi" />
  <add key="B1" value="Hello" />
</appSettings>

I mean, How can I change the value "hi" & "hello" using the key attribute(A1 & B1) ??

Thanks alot

回答1:

try this code, it works fine:

XmlDocument doc = new XmlDocument();
doc.Load("Your.xml");
XmlNodeList elementList = doc.GetElementsByTagName("add");
for (int i = 0; i < elementList.Count; i++)
{
    if(elementList[i].Attributes["key"].Value == "A1")
       elementList[i].Attributes["value"].Value = "NewValue";
}  


回答2:

if you just want to edit application configuration file this function can help you

 private static void SaveConfig(string KeyName, string value)
    {
        System.Configuration.ConfigurationManager.AppSettings[KeyName] = value;
        System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Windows.Forms.Application.ExecutablePath);
        System.Configuration.AppSettingsSection ass = config.AppSettings;
        if (ass.Settings[KeyName] != null)
            ass.Settings[KeyName].Value = value;
        else
            ass.Settings.Add(KeyName, value);
        config.Save();
    }

by calling SaveConfig("key","newvalue") you can chage the configvalue