簡體   English   中英

如何更改 c# 中 XML 文件的屬性值?

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

我有一個 XML 文件(web.config),我需要編輯每個標簽的值屬性,取決於鍵名......

這是 XML 文件的示例:

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

我的意思是,如何使用鍵屬性(A1 和 B1)更改值“hi”和“hello”?

非常感謝

試試這個代碼,它工作正常:

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

如果您只想編輯應用程序配置文件,此 function 可以幫助您

 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") 您可以更改配置值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM