关键词搜索

源码搜索 ×
×

C# 实体类序列化与反序列化一 (XmlSerializer)

发布2015-06-25浏览5985次

详情内容

  1. /// <summary>
  2. /// 实体类序列化的反序列化的类
  3. /// </summary>
  4. /// <typeparam name="T"></typeparam>
  5. public abstract class EntityClassXmlSerializer<T>
  6. {
  7. /// <summary>
  8. /// 实体类序列化成xml string
  9. /// </summary>
  10. /// <param name="entity"></param>
  11. /// <returns></returns>
  12. public static string ToXMLString(T entity)
  13. {
  14. using (MemoryStream stream = new MemoryStream())
  15. {
  16. XmlTextWriter writer = new XmlTextWriter(stream, null);
  17. XmlSerializer xml = new XmlSerializer(entity.GetType());
  18. xml.Serialize(writer, entity);
  19. writer.Formatting = Formatting.Indented;
  20. using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))
  21. {
  22. stream.Position = 0;
  23. string xmlString = sr.ReadToEnd();
  24. sr.Close();
  25. stream.Close();
  26. return xmlString;
  27. }
  28. }
  29. }
  30. /// <summary>
  31. /// 实体类反序列化
  32. /// </summary>
  33. /// <param name="xml"></param>
  34. /// <returns></returns>
  35. public static T ReadFromXML(string xml)
  36. {
  37. T entity;
  38. byte[] byts = Encoding.UTF8.GetBytes(xml);
  39. using (MemoryStream stream = new MemoryStream(byts))
  40. {
  41. XmlSerializer xs = new XmlSerializer(typeof(T));
  42. entity = (T)xs.Deserialize(stream);
  43. return entity;
  44. }
  45. }
  46. }


本文是同事亮哥所写

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载