XmlSerializeHelper.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Xml.Serialization;
  6. namespace TEAMModelOS.SDK.Helper.Common.XmlHelper
  7. {
  8. /// <summary>
  9. /// XML序列化公共处理类
  10. /// </summary>
  11. public static class XmlSerializeHelper
  12. {
  13. /// <summary>
  14. /// 将实体对象转换成XML
  15. /// </summary>
  16. /// <typeparam name="T">实体类型</typeparam>
  17. /// <param name="obj">实体对象</param>
  18. public static string XmlSerialize<T>(T obj)
  19. {
  20. try
  21. {
  22. using (StringWriter sw = new StringWriter())
  23. {
  24. Type t = obj.GetType();
  25. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  26. serializer.Serialize(sw, obj);
  27. sw.Close();
  28. return sw.ToString();
  29. }
  30. }
  31. catch (Exception ex)
  32. {
  33. throw new Exception("将实体对象转换成XML异常", ex);
  34. }
  35. }
  36. /// <summary>
  37. /// 将XML转换成实体对象
  38. /// </summary>
  39. /// <typeparam name="T">实体类型</typeparam>
  40. /// <param name="strXML">XML</param>
  41. public static T DESerializer<T>(string strXML) where T : class
  42. {
  43. try
  44. {
  45. using (StringReader sr = new StringReader(strXML))
  46. {
  47. XmlSerializer serializer = new XmlSerializer(typeof(T));
  48. return serializer.Deserialize(sr) as T;
  49. }
  50. }
  51. catch (Exception ex)
  52. {
  53. throw new Exception("将XML转换成实体对象异常", ex);
  54. }
  55. }
  56. }
  57. }