码迷,mamicode.com
首页 > 其他好文 > 详细

Xml序列化

时间:2015-11-10 19:26:15      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

一个XML序列化Helper类
技术分享
 1 /// <summary>
 2     /// XML 序列化Helper
 3     /// </summary>
 4     public class XmlHelper
 5     {
 6         /// <summary>
 7         /// 序列化
 8         /// </summary>
 9         /// <typeparam name="T">泛型</typeparam>
10         /// <param name="obj">对象</param>
11         /// <returns>字符串</returns>
12         public static string Serialize<T>(T obj)
13         {
14             if (obj == null)
15             {
16                 return string.Empty;
17             }
18 
19             using (MemoryStream stream = new MemoryStream())
20             {
21                 using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default))
22                 {
23                     var serializer = new XmlSerializer(typeof(T));
24                     XmlSerializerNamespaces xns = new XmlSerializerNamespaces();
25                     xns.Add(string.Empty, string.Empty);
26                     serializer.Serialize(writer, obj, xns);
27                     stream.Seek(0, SeekOrigin.Begin);
28                     using (StreamReader reader = new StreamReader(stream, Encoding.Default))
29                     {
30                         return reader.ReadToEnd();
31                     }
32                 }
33             }
34         }
35 
36         /// <summary>
37         /// 反序列化
38         /// </summary>
39         /// <typeparam name="T">泛型</typeparam>
40         /// <param name="xml">字符串</param>
41         /// <returns>对象</returns>
42         public static T Deserialize<T>(string xml)
43         {
44             using (MemoryStream stream = new MemoryStream())
45             {
46                 using (StreamWriter writer = new StreamWriter(stream, Encoding.Default))
47                 {
48                     writer.Write(xml);
49                     writer.Flush();
50                     stream.Seek(0, SeekOrigin.Begin);
51                     var serializer = new XmlSerializer(typeof(T));
52                     return (T)serializer.Deserialize(stream);
53                 }
54             }
55         }
56     }
XML Helper

 

Xml序列化

标签:

原文地址:http://www.cnblogs.com/lyosaki88/p/4953896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!