XmlUtility.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.IO;
  3. using System.Xml;
  4. using System.Xml.Linq;
  5. using System.Xml.Serialization;
  6. namespace LYFZ.Weixin.SDK.Helpers
  7. {
  8. public static class XmlUtility
  9. {
  10. #region 反序列化
  11. /// <summary>
  12. /// 反序列化
  13. /// </summary>
  14. /// <param name="type">类型</param>
  15. /// <param name="xml">XML字符串</param>
  16. /// <returns></returns>
  17. public static object Deserialize<T>(string xml)
  18. {
  19. try
  20. {
  21. using (StringReader sr = new StringReader(xml))
  22. {
  23. XmlSerializer xmldes = new XmlSerializer(typeof(T));
  24. return xmldes.Deserialize(sr);
  25. }
  26. }
  27. catch //(Exception e)
  28. {
  29. return null;
  30. }
  31. }
  32. /// <summary>
  33. /// 反序列化
  34. /// </summary>
  35. /// <param name="type"></param>
  36. /// <param name="xml"></param>
  37. /// <returns></returns>
  38. public static object Deserialize<T>(Stream stream)
  39. {
  40. XmlSerializer xmldes = new XmlSerializer(typeof(T));
  41. return xmldes.Deserialize(stream);
  42. }
  43. #endregion
  44. #region 序列化
  45. /// <summary>
  46. /// 序列化
  47. /// 说明:此方法序列化复杂类,如果没有声明XmlInclude等特性,可能会引发“使用 XmlInclude 或 SoapInclude 特性静态指定非已知的类型。”的错误。
  48. /// </summary>
  49. /// <param name="type">类型</param>
  50. /// <param name="obj">对象</param>
  51. /// <returns></returns>
  52. public static string Serializer<T>(T obj)
  53. {
  54. MemoryStream Stream = new MemoryStream();
  55. XmlSerializer xml = new XmlSerializer(typeof(T));
  56. try
  57. {
  58. //序列化对象
  59. xml.Serialize(Stream, obj);
  60. }
  61. catch (InvalidOperationException)
  62. {
  63. throw;
  64. }
  65. Stream.Position = 0;
  66. StreamReader sr = new StreamReader(Stream);
  67. string str = sr.ReadToEnd();
  68. sr.Dispose();
  69. Stream.Dispose();
  70. return str;
  71. }
  72. #endregion
  73. /// <summary>
  74. /// 序列化将流转成XML字符串
  75. /// </summary>
  76. /// <param name="stream"></param>
  77. /// <returns></returns>
  78. public static XDocument Convert(Stream stream)
  79. {
  80. stream.Seek(0, SeekOrigin.Begin);//强制调整指针位置
  81. using (XmlReader xr = XmlReader.Create(stream))
  82. {
  83. return XDocument.Load(xr);
  84. }
  85. }
  86. }
  87. }