XmlHelper.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Xml.Serialization;
  7. namespace SiwiFms.Helper
  8. {
  9. public class XmlHelper
  10. {
  11. /// <summary>
  12. /// xml字符串转对象
  13. /// </summary>
  14. /// <typeparam name="T"></typeparam>
  15. /// <param name="xmlStr"></param>
  16. /// <returns></returns>
  17. public static T DeserializeXmlStr<T>(string xmlStr) {
  18. if (string.IsNullOrWhiteSpace(xmlStr)) return default(T);
  19. try
  20. {
  21. using (StringReader sr = new StringReader(xmlStr))
  22. {
  23. XmlSerializer xs = new XmlSerializer(typeof(T));
  24. return (T)xs.Deserialize(sr);
  25. }
  26. }
  27. catch (Exception ex) {
  28. Console.WriteLine(ex.Message);
  29. return default(T);
  30. }
  31. }
  32. /// <summary>
  33. /// xml序列化
  34. /// </summary>
  35. /// <param name="obj"></param>
  36. /// <returns></returns>
  37. public static string SerializeXmlStr(object obj) {
  38. if (obj == null) return string.Empty;
  39. MemoryStream stream = new MemoryStream();
  40. StreamReader sr = null;
  41. try
  42. {
  43. XmlSerializer xs = new XmlSerializer(obj.GetType());
  44. xs.Serialize(stream, obj);
  45. stream.Position = 0;
  46. sr = new StreamReader(stream);
  47. return sr.ReadToEnd();
  48. }
  49. catch (Exception ex)
  50. {
  51. Console.WriteLine(ex.Message);
  52. return "";
  53. }
  54. finally {
  55. if (sr != null)
  56. {
  57. sr.Dispose();
  58. }
  59. stream.Dispose();
  60. }
  61. }
  62. }
  63. }