/*------------------------------------------------------------------------- * 功能描述:MenuConfigParser * 作者:xulisong * 创建时间: 2019/3/12 14:43:05 * 版本号:v1.0 * -------------------------------------------------------------------------*/ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml; using FWindSoft.Tools; namespace FWindSoft.Revit.Menu { public class MenuConfigParser { public static MenuConfig Load(string path) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(path); return Load(xmlDoc); } public static MenuConfig LoadContent(string xmlContent) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlContent); return Load(xmlDoc); } public static MenuConfig Load(Stream steam) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(steam); return Load(xmlDoc); } public static MenuConfig Load(XmlDocument xmlDocument) { MenuConfig config = new MenuConfig(); var root = xmlDocument.SelectSingleNode(@"Menu"); if (root == null) { return config; } Dictionary map = new Dictionary(); map["Tabs"] = @"Tabs/Tab"; map["Panels"] = @"Panels/Panel"; map["Buttons"] = @"Buttons/Button"; #region 解析tab var configProperties = typeof(MenuConfig).GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var keyValue in map) { var property = configProperties.FirstOrDefault(p => p.Name == keyValue.Key); if (property == null) { continue; } var nodes = root.SelectNodes(keyValue.Value); if (nodes != null) { foreach (XmlNode node in nodes) { var revitObject = CreateObject(node,property.PropertyType.GenericTypeArguments[0]); ((IList) property.GetValue(config)).Add(revitObject); } } } #endregion return config; } #region 解析节点通用方法 private static T CreateObject(XmlNode xmlNode) { T t = Activator.CreateInstance(); PropertyInfo[] properties = t.GetType().GetProperties(); for (int i = 0; i < properties.Length; i++) { PropertyInfo propertyInfo = properties[i]; try { var currentNode = xmlNode.SelectSingleNode(string.Format("/{0}", propertyInfo.Name)); if (currentNode != null) { propertyInfo.SetValue(t, TypeUtil.ChangeType(currentNode.InnerText, propertyInfo.PropertyType) ?? "", null); } } catch (Exception ex) { } } return t; } private static object CreateObject(XmlNode xmlNode,Type targetType) { object t = Activator.CreateInstance(targetType); PropertyInfo[] properties = t.GetType().GetProperties(); for (int i = 0; i < properties.Length; i++) { PropertyInfo propertyInfo = properties[i]; try { var currentNode = xmlNode.SelectSingleNode(string.Format("{0}", propertyInfo.Name)); if (currentNode != null) { propertyInfo.SetValue(t, TypeUtil.ChangeType(currentNode.InnerText, propertyInfo.PropertyType) ?? "", null); } } catch (Exception ex) { } } return t; } #endregion } }