XML操作

发布时间 2023-12-21 10:36:02作者: 回首起了风沙

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