XmlSerializeHelper.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.IO;
  3. using System.Xml.Serialization;
  4. namespace PaintDotNet.Base.CommTool
  5. {
  6. /// <summary>
  7. /// XML序列化公共处理类
  8. /// </summary>
  9. public static class XmlSerializeHelper
  10. {
  11. /// <summary>
  12. /// 将实体对象转换成XML
  13. /// </summary>
  14. /// <typeparam name="T">实体类型</typeparam>
  15. /// <param name="obj">实体对象</param>
  16. public static string XmlSerialize<T>(T obj)
  17. {
  18. try
  19. {
  20. using (StringWriter sw = new StringWriter())
  21. {
  22. Type t = obj.GetType();
  23. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  24. serializer.Serialize(sw, obj);
  25. sw.Close();
  26. return sw.ToString();
  27. }
  28. }
  29. catch (Exception ex)
  30. {
  31. throw new Exception("", ex); // ("将实体对象转换成XML异常", ex); //("", exception); //
  32. }
  33. }
  34. /// <summary>
  35. /// 将XML转换成实体对象
  36. /// </summary>
  37. /// <typeparam name="T">实体类型</typeparam>
  38. /// <param name="strXML">XML</param>
  39. public static T DESerializer<T>(string strXML) where T : class
  40. {
  41. try
  42. {
  43. using (StringReader sr = new StringReader(strXML))
  44. {
  45. XmlSerializer serializer = new XmlSerializer(typeof(T));
  46. return serializer.Deserialize(sr) as T;
  47. }
  48. }
  49. catch (Exception ex)
  50. {
  51. throw new Exception("", ex); // ("将XML转换成实体对象异常", ex);
  52. }
  53. }
  54. /// <summary>
  55. /// 将实体对象转换成XML
  56. /// </summary>
  57. /// <typeparam name="T">实体类型</typeparam>
  58. /// <param name="obj">实体对象</param>
  59. public static void Save<T>(T obj, string path)
  60. {
  61. try
  62. {
  63. using (var wirter = new FileStream(path, (FileMode)FileAccess.Write))
  64. {
  65. Type t = obj.GetType();
  66. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  67. serializer.Serialize(wirter, obj);
  68. wirter.Close();
  69. }
  70. }
  71. catch (Exception ex)
  72. {
  73. throw new Exception("", ex);
  74. }
  75. }
  76. /// <summary>
  77. /// 将XML转换成实体对象
  78. /// </summary>
  79. /// <typeparam name="T">实体类型</typeparam>
  80. /// <param name="strXML">XML</param>
  81. public static T Load<T>(string path) where T : class
  82. {
  83. try
  84. {
  85. using (var reader = new FileStream(path, FileMode.Open))
  86. {
  87. XmlSerializer xml = new XmlSerializer(typeof(T));
  88. var obj = xml.Deserialize(reader);
  89. reader.Close();
  90. return obj as T;
  91. }
  92. }
  93. catch (Exception ex)
  94. {
  95. throw new Exception("", ex);
  96. }
  97. }
  98. }
  99. }