1 public class XMLHealper
2 {
3 ///
4 /// 将自定义对象序列化为XML字符串
5 ///
6 /// 自定义对象实体
7 /// 序列化后的XML字符串
8 public static string SerializeToXml(T myObject)
9 {
10 if (myObject != null)
11 {
12 XmlSerializer xs = new XmlSerializer(typeof(T));
13
14 MemoryStream stream = new MemoryStream();
15 XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
16 writer.Formatting = Formatting.None;//缩进
17 xs.Serialize(writer, myObject);
18
19 stream.Position = 0;
20 StringBuilder sb = new StringBuilder();
21 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
22 {
23 string line;
24 while ((line = reader.ReadLine()) != null)
25 {
26 sb.Append(line);
27 }
28 reader.Close();
29 }
30 writer.Close();
31 return sb.ToString();
32 }
33 return string.Empty;
34 }
35
36 ///
37 /// 将XML字符串反序列化为对象
38 ///
39 /// 对象类型
40 /// XML字符
41 ///
42 public static T DeserializeToObject(string xmlContent)
43 {
44 T myObject;
45 XmlSerializer serializer = new XmlSerializer(typeof(T));
46 StringReader reader = new StringReader(xmlContent);
47 myObject = (T)serializer.Deserialize(reader);
48 reader.Close();
49 return myObject;
50 }
51
52 public static T RreadXML(string filePath)
53 {
54 return DeserializeToObject(FileHelper.ReadFile(filePath));
55 }
56 public static bool WriteXML(string xmlContent,string filePath)
57 {
58 return FileHelper.WriteFile(xmlContent, filePath);
59 }
60 public static bool WriteXML(T contentModel,string filePath)
61 {
62 string xmlContent = SerializeToXml(contentModel);
63 return FileHelper.WriteFile(xmlContent, filePath);
64 }
65
66 }