XML的序列化与反序列化

时间:2021-10-07 20:19:10

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

直接上代码:

     public static class Utility
{
public static T Deserialize<T>(string path)
{
try
{
using (var fs = new StreamReader(path))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
var result = (T)serializer.Deserialize(fs);
return result;
}
}
catch (Exception)
{ }
return default(T);
} public static void Serialize<T>(T serializableObject, string path)
{
try
{
using (var sw = new StringWriter())
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(sw, serializableObject); File.WriteAllText(path, sw.GetStringBuilder().ToString());
}
}
catch (Exception)
{ }
}
}

对应的对象:(两种)

      [XmlRoot("root")]
public class SavedMessage
{
public int UserId { get; set; }
[XmlArray("messages")]
[XmlArrayItem("message", Type = typeof(string))]
public List<string> Messages { get; set; }
} [XmlRoot("root")]
public class SavedUser
{
[XmlArray("users")]
[XmlArrayItem("user", Type = typeof(User))]
public List<User> Users { get; set; }
}

使用方法:

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属性一致的)

 // users
<?xml version="1.0" encoding="utf-16"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<users>
<user>
<Id></Id>
<Name>John</Name>
</user>
<user>
<Id></Id>
<Name>Mary</Name>
</user>
</users>
</root> // message
<?xml version="1.0" encoding="utf-16"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UserId></UserId>
<messages>
<message>aaa</message>
<message>bbb</message>
<message>ccc</message>
</messages>
</root>