How can I change an attribute value of a XML file in c#?

主宰稳场 提交于 2019-12-06 12:14:40

问题


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



来源:https://stackoverflow.com/questions/6167543/how-can-i-change-an-attribute-value-of-a-xml-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!