XmlSerializeHelper.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Xml.Serialization;
  8. using SenseShield;
  9. namespace SmartCoalApplication.Base.CommTool
  10. {
  11. /// <summary>
  12. /// XML序列化公共处理类
  13. /// </summary>
  14. public static class XmlSerializeHelper
  15. {
  16. /// <summary>
  17. /// 将实体对象转换成XML
  18. /// </summary>
  19. /// <typeparam name="T">实体类型</typeparam>
  20. /// <param name="obj">实体对象</param>
  21. public static string XmlSerialize<T>(T obj)
  22. {
  23. try
  24. {
  25. using (StringWriter sw = new StringWriter())
  26. {
  27. Type t = obj.GetType();
  28. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  29. serializer.Serialize(sw, obj);
  30. sw.Close();
  31. return sw.ToString();
  32. }
  33. }
  34. catch (Exception ex)
  35. {
  36. throw new Exception("", ex); // ("将实体对象转换成XML异常", ex); //("", exception); //
  37. }
  38. }
  39. static bool IS_INIT = false;
  40. /// <summary>
  41. /// 将XML转换成实体对象
  42. /// </summary>
  43. /// <typeparam name="T">实体类型</typeparam>
  44. /// <param name="strXML">XML</param>
  45. public static T DESerializer<T>(string strXML) where T : class
  46. {
  47. try
  48. {
  49. //if (!IS_INIT)
  50. //{
  51. // //许可ID是 10000 或者 4 都可以
  52. // DogDecrypting.decrypting(new uint[] { 10000, 4, 41, 42, 3,5 });
  53. // IS_INIT = true;
  54. //}
  55. using (StringReader sr = new StringReader(strXML))
  56. {
  57. XmlSerializer serializer = new XmlSerializer(typeof(T));
  58. return serializer.Deserialize(sr) as T;
  59. }
  60. }
  61. catch (Exception ex)
  62. {
  63. throw new Exception("", ex); // ("将XML转换成实体对象异常", ex);
  64. }
  65. }
  66. }
  67. }