using HighWayIot.Log4net; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace HighWayIot.Common.XmlConfig { /// /// 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("DeviceConfig"); foreach (XmlNode role in node) { XmlAttribute pageName = (XmlAttribute)role.Attributes.GetNamedItem("Name"); list.Add(pageName.Value); } return list; } /// /// 初级目录InnerText配置读取 /// /// public string BaseInnerTextReader(string label) { xmlDocument.Load($"{Path}\\Configuration.xml"); XmlNode root = xmlDocument.DocumentElement; XmlNode node = root.SelectSingleNode(label); string path = node.InnerText; return path; } 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; } } }