经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
XML操作类
来源:cnblogs  作者:旭_东  时间:2018/10/17 9:10:53  对本文有异议
  1. 1 using System;
  2. 2 using System.Collections.Generic;
  3. 3 using System.IO;
  4. 4 using System.Reflection;
  5. 5 using System.Text;
  6. 6 using System.Xml;
  7. 7
  8. 8 namespace CommonLib
  9. 9 {
  10. 10 public class XMLHelper
  11. 11 {
  12. 12 public XMLHelper()
  13. 13 {
  14. 14
  15. 15 }
  16. 16
  17. 17 public void Create<T>(string xmlPath, List<T> updateXMLs)
  18. 18 {
  19. 19 XmlDocument document = new XmlDocument();
  20. 20 Type type = typeof(T);
  21. 21 document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-8", null));
  22. 22 XmlElement root = document.CreateElement(type.Name + "Collection");
  23. 23 PropertyInfo[] properties = type.GetProperties();
  24. 24 foreach (var updateXml in updateXMLs)
  25. 25 {
  26. 26 XmlElement parentElememt = document.CreateElement(type.Name);
  27. 27 foreach (PropertyInfo property in properties)
  28. 28 {
  29. 29 XmlElement element = document.CreateElement(property.Name);
  30. 30 element.InnerText = updateXml.GetPropertyValue(property).ToString();
  31. 31 parentElememt.AppendChild(element);
  32. 32 }
  33. 33 root.AppendChild(parentElememt);
  34. 34 }
  35. 35 document.AppendChild(root);
  36. 36 document.Save(xmlPath);
  37. 37 }
  38. 38
  39. 39 public List<T> Read<T>(string updatexml) where T : new()
  40. 40 {
  41. 41 XmlDocument document = new XmlDocument();
  42. 42 document.Load(updatexml);
  43. 43 List<T> tList = new List<T>();
  44. 44 foreach (XmlNode node in document.ChildNodes[1].ChildNodes)
  45. 45 {
  46. 46 T t = new T();
  47. 47 foreach (XmlNode childNode in node.ChildNodes)
  48. 48 {
  49. 49 t.SetPropertyValue(childNode.Name, childNode.InnerText);
  50. 50 }
  51. 51 tList.Add(t);
  52. 52 }
  53. 53 return tList;
  54. 54 }
  55. 55
  56. 56
  57. 57 public List<T> ReadContext<T>(string context) where T : new()
  58. 58 {
  59. 59 XmlDocument document = new XmlDocument();
  60. 60 byte[] bytes = Encoding.UTF8.GetBytes(context);
  61. 61 MemoryStream ms = new MemoryStream(bytes);
  62. 62 ms.Seek(0, SeekOrigin.Begin);
  63. 63 document.Load(ms);
  64. 64 List<T> tList = new List<T>();
  65. 65 foreach (XmlNode node in document.ChildNodes[1].ChildNodes)
  66. 66 {
  67. 67 T t = new T();
  68. 68 foreach (XmlNode childNode in node.ChildNodes)
  69. 69 {
  70. 70 t.SetPropertyValue(childNode.Name, childNode.InnerText);
  71. 71 }
  72. 72 tList.Add(t);
  73. 73 }
  74. 74 return tList;
  75. 75 }
  76. 76 }
  77. 77 }

生成与对象一致的XML

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号