using System; using System.Xml; using System.Reflection; using System.Collections.Generic; using SHJX.Service.Common.Logging; using Microsoft.Extensions.Logging; namespace SHJX.Service.Common.ReadXML { /// /// 抽象配置类。默认使用一个xml文件保存配置信息。每个具体的实现类中应该从该xml的不同节点获取相应的配置信息。 /// public abstract class AbstractConfiguration { //private static readonly ILogger logger = LogFactory.BuildLogger(typeof(AbstractConfiguration)); private XmlDocument configFile; private static string fileName; public void Load(string source) { fileName = source; configFile = new XmlDocument(); var settings = new XmlReaderSettings { IgnoreComments = true //忽略文档里面的注释 }; var reader = XmlReader.Create(source, settings); configFile.Load(reader); } /// /// 无参构造 /// /// /// public T ConvertTo() { var type = typeof(T); if (type.BaseType != typeof(AbstractConfiguration)) return default; var obj = Activator.CreateInstance(type, true); var baseObj = (AbstractConfiguration)obj; baseObj.configFile = configFile; return (T)obj; } /// /// 有参构造 /// /// /// /// public T ConvertTo(object[] args) { var type = typeof(T); if (type.BaseType != typeof(AbstractConfiguration)) return default; var obj = Activator.CreateInstance(type, args); var baseObj = (AbstractConfiguration)obj; baseObj.configFile = this.configFile; return (T)obj; } /// /// 获取单值 /// /// 节点地址 /// protected string ReadSingleValue(string xmlPath) { var xn = configFile.SelectSingleNode(xmlPath); if (xn != null) { switch (xn.NodeType) { case XmlNodeType.Attribute: return xn.Value; case XmlNodeType.Element: return xn.InnerText; } } //logger.LogError("Failed to find an available value using xPath {0}. ", xmlPath); return string.Empty; } /// /// 获取值的集合 /// /// /// protected XmlNodeList ReadListValue(string xmlPath) => configFile.SelectNodes(xmlPath); /// /// 获取字典集合 /// /// /// protected IEnumerable> ReadSetValue(string xmlPath) { var setValues = new List>(); var xnList = ReadListValue(xmlPath); if (xnList != null) { for (int i = 0; i < xnList.Count; i++) { var xn = xnList[i]; var item = new Dictionary(); var xaCollection = xn.Attributes; if (xaCollection is not null) for (var j = 0; j < xaCollection.Count; j++) { item.Add(xaCollection[j].Name, xaCollection[j].Value); } setValues.Add(item); } } else { //logger.LogInformation("Cannot find any set definition using path [{0}].", xmlPath); } return setValues; } /// /// 写入单值 /// /// /// protected void WriteSingleValue(string xmlPath, object value) { var xn = configFile.SelectSingleNode(xmlPath); if (xn != null) { switch (xn.NodeType) { case XmlNodeType.Attribute: xn.Value = value.ToString(); break; case XmlNodeType.Element: xn.InnerText = value.ToString(); break; } } configFile.Save(fileName); } } }