XmlUtils.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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;
  8. using System.Xml.Serialization;
  9. namespace Utils
  10. {
  11. public static class XmlUtils
  12. {
  13. /// <summary>
  14. /// 将object转换成xml格式的string
  15. /// </summary>
  16. /// <param name="o"></param>
  17. /// <returns></returns>
  18. public static string Object2XmlString(Object o)
  19. {
  20. XmlWriterSettings settings = new XmlWriterSettings();
  21. settings.Indent = false;
  22. settings.NewLineHandling = NewLineHandling.None;
  23. settings.Encoding = Encoding.UTF8;
  24. settings.OmitXmlDeclaration = true;
  25. XmlSerializer xs = new XmlSerializer(o.GetType());
  26. using (StringWriter ws = new StringWriter())
  27. {
  28. XmlWriter w = XmlWriter.Create(ws, settings);
  29. try
  30. {
  31. XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
  32. namespaces.Add(string.Empty, string.Empty);
  33. xs.Serialize(w, o, namespaces);
  34. return ws.ToString();
  35. } finally
  36. {
  37. w.Dispose();
  38. }
  39. }
  40. }
  41. /// <summary>
  42. /// 将xml格式的string转换层实体类
  43. /// </summary>
  44. /// <typeparam name="T"></typeparam>
  45. /// <param name="xmlStr"></param>
  46. /// <returns></returns>
  47. public static T XmlString2Object<T>(string xmlStr)
  48. {
  49. using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlStr)))
  50. {
  51. XmlSerializer serializer = new XmlSerializer(typeof(T));
  52. return (T)serializer.Deserialize(stream);
  53. }
  54. }
  55. /// <summary>
  56. /// 将xml格式stream转换层实体类
  57. /// </summary>
  58. /// <typeparam name="T"></typeparam>
  59. /// <param name="stream"></param>
  60. /// <returns></returns>
  61. public static T XmlStream2Object<T>(Stream stream)
  62. {
  63. XmlSerializer serializer = new XmlSerializer(typeof(T));
  64. return (T)serializer.Deserialize(stream);
  65. }
  66. /// <summary>
  67. /// 将xml格式文件转换层实体类
  68. /// </summary>
  69. /// <typeparam name="T"></typeparam>
  70. /// <param name="fileName"></param>
  71. /// <returns></returns>
  72. public static T XmlFile2Object<T>(string fileName)
  73. {
  74. using (Stream stream = new FileStream(fileName, FileMode.Open))
  75. {
  76. XmlSerializer serializer = new XmlSerializer(typeof(T));
  77. return (T)serializer.Deserialize(stream);
  78. }
  79. }
  80. }
  81. }