using HighWayIot.Log4net; using HighWayIot.Repository.service; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace HighWayIot.Winform.Business { /// /// XML读写类 /// public class XmlUtil { private static readonly Lazy lazy = new Lazy(() => new XmlUtil()); public static XmlUtil Instance { get { return lazy.Value; } } /// /// XML读写实例 /// XmlDocument xmlDocument = new XmlDocument(); /// /// 运行时路径 /// private string Path = System.Environment.CurrentDirectory; /// /// 配置读取 /// /// public List ConfigReader() { List list = new List(); xmlDocument.Load($"{Path}\\Configuration.xml"); XmlNode root = xmlDocument.DocumentElement; XmlNode node = root.SelectSingleNode("RoleConfig"); foreach (XmlNode role in node) { XmlAttribute pageName = (XmlAttribute)role.Attributes.GetNamedItem("PageName"); XmlAttribute roleIndex = (XmlAttribute)role.Attributes.GetNamedItem("RoleIndex"); int.TryParse(roleIndex.Value, out int index); list.Add(new RoleConfig() { PageName = pageName.Value, RoleIndex = index, }); } return list; } /// /// 读取导出路径配置 /// /// public string ExportPathReader() { xmlDocument.Load($"{Path}\\Configuration.xml"); XmlNode root = xmlDocument.DocumentElement; XmlNode node = root.SelectSingleNode("ExportConfig"); XmlAttribute path = (XmlAttribute)node.Attributes.GetNamedItem("Path"); return path.Value; } public void ExportPathWriter(string path) { //xmlDocument.Load($"{Path}\\Configuration.xml"); //XmlNode root = xmlDocument.DocumentElement; //XmlNode node = root.SelectSingleNode("ExportConfig"); //node.Attributes["Path"].Value = path; //xmlDocument.Save($"{Path}\\Configuration.xml"); // 参数验证 if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException(nameof(path), "导出路径不能为空"); } try { // 加载XML文档 xmlDocument.Load($"{Path}\\Configuration.xml"); // 获取根节点 XmlNode root = xmlDocument.DocumentElement ?? throw new InvalidOperationException("XML文档没有根元素"); // 查找ExportConfig节点 XmlNode node = root.SelectSingleNode("ExportConfig") ?? throw new InvalidOperationException("找不到ExportConfig节点"); // 获取Path属性 XmlAttribute pathAttribute = node.Attributes?["Path"] ?? throw new InvalidOperationException("ExportConfig节点没有Path属性"); // 设置新值 pathAttribute.Value = path; // 保存修改 xmlDocument.Save($"{Path}\\Configuration.xml"); } catch (Exception ex) { // 记录日志或处理特定异常 LogHelper.Instance.Error("保存导出路径配置失败", ex); } } } public class RoleConfig { /// /// 页面名称 /// public string PageName { get; set; } /// /// 规则编号 /// public int RoleIndex { get; set; } } public class ExportPathConfig { public string ExportConfig { get; set; } public string Config { get; set; } } }