Xml.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*********************************************************************************
  2. *Author: OnClick
  3. *Version: 1.0
  4. *UnityVersion: 2017.2.3p3
  5. *Date: 2019-01-26
  6. *Description:
  7. *History:
  8. **********************************************************************************/
  9. using System.IO;
  10. using System.Text;
  11. using System.Xml.Serialization;
  12. namespace IFramework.Serialization
  13. {
  14. #pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释
  15. public interface IXmlHelper
  16. {
  17. string ToXml<T>(T t);
  18. T FromXml<T>(string xmlString);
  19. }
  20. public class Xml
  21. {
  22. public static IXmlHelper helper { get; set; }
  23. static Xml()
  24. {
  25. helper =new DefaultXmlHelper();
  26. }
  27. public static string ToXml<T>(T t)
  28. {
  29. return helper.ToXml(t);
  30. }
  31. public static T FromXml<T>(string xmlString)
  32. {
  33. return helper.FromXml<T>(xmlString);
  34. }
  35. }
  36. internal class DefaultXmlHelper : IXmlHelper
  37. {
  38. public T FromXml<T>(string xmlString)
  39. {
  40. using (TextReader reader = new StringReader(xmlString))
  41. {
  42. return (T)new XmlSerializer(typeof(T)).Deserialize(reader);
  43. }
  44. }
  45. public string ToXml<T>(T t)
  46. {
  47. StringBuilder sb = new StringBuilder();
  48. using (TextWriter writer = new StringWriter(sb))
  49. {
  50. new XmlSerializer(typeof(T)).Serialize(writer, t);
  51. }
  52. return sb.ToString();
  53. //using (MemoryStream ms = new MemoryStream())
  54. //{
  55. // new XmlSerializer(typeof(T)).Serialize(ms, t);
  56. // return Encoding.UTF8.GetString(ms.ToArray());
  57. //}
  58. }
  59. }
  60. #pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释
  61. }