XML的序列化与反序列化

开发时会把数据持久化成xml格式,当然可以用xmlwriter来实现,不过感觉不方便,而且很繁琐。推荐使用直接序列化、反序列化对象的方法来处理。

直接上代码:

 1     public static class Utility

 2     {

 3         public static T Deserialize<T>(string path)

 4         {

 5             try

 6             {

 7                 using (var fs = new StreamReader(path))

 8                 {

 9                     XmlSerializer serializer = new XmlSerializer(typeof(T));

10                     var result = (T)serializer.Deserialize(fs);

11                     return result;

12                 }

13             }

14             catch (Exception)

15             { }

16             return default(T);

17         }

18 

19         public static void Serialize<T>(T serializableObject, string path)

20         {

21             try

22             {

23                 using (var sw = new StringWriter())

24                 {

25                     XmlSerializer serializer = new XmlSerializer(typeof(T));

26                     serializer.Serialize(sw, serializableObject);

27 

28                     File.WriteAllText(path, sw.GetStringBuilder().ToString());

29                 }

30             }

31             catch (Exception)

32             { }

33         }

34     }

 

对应的对象:(两种)

 1      [XmlRoot("root")]

 2     public class SavedMessage

 3     {

 4         public int UserId { get; set; }

 5         [XmlArray("messages")]

 6         [XmlArrayItem("message", Type = typeof(string))]

 7         public List<string> Messages { get; set; }

 8     }

 9 

10     [XmlRoot("root")]

11     public class SavedUser

12     {

13         [XmlArray("users")]

14         [XmlArrayItem("user", Type = typeof(User))]

15         public List<User> Users { get; set; }

16     }

 

使用方法:

1 // save to file 2 Utility.Serialize<SavedMessage>(savedMessage, "Message.xml"); 3 4 // read from file 5 var messageModel = Utility.Deserialize<SavedMessage>("Message.xml");

 

生成的文件格式:(xml里的结点是和对象上的xml属性一致的)

 1 // users

 2 <?xml version="1.0" encoding="utf-16"?>

 3 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

 4   <users>

 5     <user>

 6       <Id>1</Id>

 7       <Name>John</Name>

 8     </user>

 9     <user>

10       <Id>2</Id>

11       <Name>Mary</Name>

12     </user>

13   </users>

14 </root>

15 

16 

17 // message

18 <?xml version="1.0" encoding="utf-16"?>

19 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

20   <UserId>1</UserId>

21   <messages>

22     <message>aaa</message>

23     <message>bbb</message>

24     <message>ccc</message>

25   </messages>

26 </root>

 

你可能感兴趣的:(反序列化)