[英]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.