xml文件的加载与配置

前端之家收集整理的这篇文章主要介绍了xml文件的加载与配置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、xml配置类设计 ---AdminConfigManager.cs

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace XMLTest
{
public static class AdminConfigManager
{
public static IList<AdminUser> AdminUsers { get; } = new List<AdminUser>();

#region 加载、保存相关
/// <summary>
/// 获取或设置配置文件路径。
/// </summary>
public static string ConfigFilePath { get; set; }

/// <summary>
/// 加载配置。
/// </summary>
public static void LoadConfig()
{
XElement root = XElement.Load(ConfigFilePath);
AdminUsers.Clear();
foreach (XElement element in root.Elements("AdminUser"))
{
AdminUser adminUser = new AdminUser();
adminUser.Id = (string)element.Attribute("Id");
adminUser.Name = (string)element.Attribute("Name");
AdminUsers.Add(adminUser);
}
}

/// <summary>
/// 保存配置。
/// </summary>
public static void SaveConfig()
{
XDocument doc = new XDocument(
new XDeclaration("1.0","utf-8","yes"),
new XElement("AdminConfig",
from adminUser in AdminUsers
select new XElement("AdminUser",
new XAttribute("Id",adminUser.Id),
new XAttribute("Name",adminUser.Name))));

doc.Save(ConfigFilePath);
}
#endregion
}

public sealed class AdminUser
{
public string Id { get; set; }
public string Name { get; set; }
}
}

二、以控制台程序为例,调用示例

using System; using System.Collections.Generic; namespace XMLTest { class Program { static void Main(string[] args) { AdminConfigManager.ConfigFilePath = @"E:/AdminUserConfig.xml";//配置xml文件路径 AdminConfigManager.LoadConfig();//加载文件 IList<AdminUser> andminUsers = AdminConfigManager.AdminUsers; //新增 AdminUser addAdminUser = new AdminUser(); addAdminUser.Id = "RJ"; addAdminUser.Name = "任静"; AdminConfigManager.AdminUsers.Add(addAdminUser); AdminConfigManager.SaveConfig(); //删除 //AdminUser deleteAdminUser = AdminConfigManager.AdminUsers.Where(u => u.Id == "RJ").First(); //AdminConfigManager.AdminUsers.Remove(deleteAdminUser); //AdminConfigManager.SaveConfig(); Console.ReadKey(); } } }

原文链接:/xml/295435.html

猜你在找的XML相关文章