How can I change an attribute value of a XML file

2020-07-24 04:42发布

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

2条回答
可以哭但决不认输i
2楼-- · 2020-07-24 05:26

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";
}  
查看更多
狗以群分
3楼-- · 2020-07-24 05:36

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

查看更多
登录 后发表回答