XML操作
XML操作
因XML的易于读取和修改,因此可以存放程序的可配置项
C#中的XML操作
通过ConfigurationManager类读取
通过该方法只能实现Get操作。并且在Winform框架下,无法实现配置文件的热加载
private static string apiUrl = ConfigurationManager.AppSettings["Url"];
通过XmlDocument类操作
通过XmlDocument可以实现对XML的增删改查操作
public static void UpdateOrInsertAppSetting(string key, string value)
{
// Load the app.config file as an XmlDocument
XmlDocument doc = new XmlDocument();
//配置文件的路径,这样用默认路径
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
// Modify the XML structure or content
// For instance, let's add or update an element in the appSettings section
XmlNode appSettingsNode = doc.SelectSingleNode("//appSettings");
// Check if the appSettings node exists
if (appSettingsNode == null)
{
// If it doesn't exist, create a new appSettings node
XmlElement root = doc.DocumentElement;
appSettingsNode = doc.CreateElement("appSettings");
root.AppendChild(appSettingsNode);
}
// Check if the key exists, update if it does, else add a new key-value pair
XmlNode node = appSettingsNode.SelectSingleNode($"//add[@key='{key}']");
if (node != null)
{
node.Attributes["value"].Value = value;
}
else
{
XmlElement newElement = doc.CreateElement("add");
newElement.SetAttribute("key", key);
newElement.SetAttribute("value", value);
appSettingsNode.AppendChild(newElement);
}
// Save the changes back to the app.config file
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
public static string ReadXML(string key)
{
XmlDocument doc = new XmlDocument();
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
XmlNode appSettingsNode = doc.SelectSingleNode("//appSettings");
// Check if the appSettings node exists
if (appSettingsNode == null)
{
// If it doesn't exist, create a new appSettings node
XmlElement root = doc.DocumentElement;
appSettingsNode = doc.CreateElement("appSettings");
root.AppendChild(appSettingsNode);
}
// Check if the key exists, update if it does, else add a new key-value pair
XmlNode node = appSettingsNode.SelectSingleNode($"//add[@key='{key}']");
if (node != null)
{
return node.Attributes["value"].Value;
}
else
{
return null;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统