XmlHelper.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Xml;
  4. namespace Common
  5. {
  6. public class XmlHelper
  7. {
  8. /// <summary>
  9. /// 将XML内容转换成目标对象实体集合
  10. /// </summary>
  11. /// <typeparam name="T">目标对象实体</typeparam>
  12. /// <param name="FileName">完整文件名(根目录下只需文件名称)</param>
  13. /// <param name="WrapperNodeName"></param>
  14. /// <returns></returns>
  15. public static List<T> ConvertXMLToObject<T>(string FileName, string WrapperNodeName = "UrlSetting")
  16. {
  17. XmlDocument doc = new XmlDocument();
  18. doc.Load(FileName);
  19. List<T> result = new List<T>();
  20. var TType = typeof(T);
  21. XmlNodeList nodeList = doc.ChildNodes;
  22. if (!string.IsNullOrEmpty(WrapperNodeName))
  23. {
  24. foreach (XmlNode node in doc.ChildNodes)
  25. {
  26. if (node.Name == WrapperNodeName)
  27. {
  28. nodeList = node.ChildNodes;
  29. break;
  30. }
  31. }
  32. }
  33. object oneT = null;
  34. foreach (XmlNode node in nodeList)
  35. {
  36. if (node.NodeType == XmlNodeType.Comment || node.NodeType == XmlNodeType.XmlDeclaration) continue;
  37. oneT = TType.Assembly.CreateInstance(TType.FullName);
  38. foreach (XmlNode item in node.ChildNodes)
  39. {
  40. if (item.NodeType == XmlNodeType.Comment) continue;
  41. var property = TType.GetProperty(item.Name);
  42. if (property != null)
  43. property.SetValue(oneT, Convert.ChangeType(item.InnerText, property.PropertyType), null);
  44. }
  45. result.Add((T)oneT);
  46. }
  47. return result;
  48. }
  49. ///// <summary>
  50. ///// 从作业数据地图中获取配置信息
  51. ///// </summary>
  52. ///// <param name="datamap">作业数据地图</param>
  53. ///// <returns></returns>
  54. //public static FCSConfig GetConfigFromDataMap(JobDataMap datamap)
  55. //{
  56. // FCSConfig config = new FCSConfig();
  57. // var properties = typeof(FCSConfig).GetProperties();
  58. // foreach (PropertyInfo info in properties)
  59. // {
  60. // if (info.PropertyType == typeof(string))
  61. // info.SetValue(config, datamap.GetString(info.Name), null);
  62. // else if (info.PropertyType == typeof(Int32))
  63. // info.SetValue(config, datamap.GetInt(info.Name), null);
  64. // }
  65. // return config;
  66. //}
  67. }
  68. }