如何在c#中更改XML文件的属性值

本文关键字:文件 XML 属性 | 更新日期: 2023-09-27 17:57:59

我有一个XML文件(web.config),我需要编辑每个标记的value属性,这取决于密钥名称。。。

这是XML文件的一个示例:

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

我的意思是,我怎样才能改变值"hi"&使用键属性(A1&B1)的"你好"??

感谢

如何在c#中更改XML文件的属性值

试试这个代码,它工作得很好:

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";
}  

如果您只想编辑应用程序配置文件这个功能可以帮助你

 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();
    }

通过调用SaveConfig("key"、"newvalue"),您可以更改配置值