C# XML与对象互相转换

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.Xml.Serialization;
 5 using System.IO;
 6 using System.Xml;
 7 
 8 namespace Common
 9 {
10     public class XmlUtility
11     {
12         /// <summary>
13         /// 将自定义对象序列化为XML字符串
14         /// </summary>
15         /// <param name="myObject">自定义对象实体</param>
16         /// <returns>序列化后的XML字符串</returns>
17         public static string SerializeToXml<T>(T myObject)
18         {
19             if (myObject != null)
20             {
21                 XmlSerializer xs = new XmlSerializer(typeof(T));
22 
23                 MemoryStream stream = new MemoryStream();
24                 XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
25                 writer.Formatting = Formatting.None;//缩进
26                 xs.Serialize(writer, myObject);
27 
28                 stream.Position = 0;
29                 StringBuilder sb = new StringBuilder();
30                 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
31                 {
32                     string line;
33                     while ((line = reader.ReadLine()) != null)
34                     {
35                         sb.Append(line);
36                     }
37                     reader.Close();
38                 }
39                 writer.Close();
40                 return sb.ToString();
41             }
42             return string.Empty;
43         }
44 
45         /// <summary>
46         /// 将XML字符串反序列化为对象
47         /// </summary>
48         /// <typeparam name="T">对象类型</typeparam>
49         /// <param name="xml">XML字符</param>
50         /// <returns></returns>
51         public static T DeserializeToObject<T>(string xml)
52         {
53             T myObject;
54             XmlSerializer serializer = new XmlSerializer(typeof(T));
55             StringReader reader = new StringReader(xml);
56             myObject = (T)serializer.Deserialize(reader);
57             reader.Close();
58             return myObject;
59         }
60     }
61 }
原文地址:https://www.cnblogs.com/servant/p/4462446.html