序列化和反序列化到XML的最简单方法是什么?
本文关键字:最简单 方法 是什么 XML 反序列化 序列化 | 更新日期: 2023-09-27 18:09:10
class Server
{
public int ID { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string AdminEmail { get; set; }
}
我需要序列化到XML并反序列化List<Server> _servers
;
谢谢你的帮助!
使用XmlSerializer
类:
var servers = new List<Server>();
// fill servers...
var serializer = new XmlSerializer(typeof(List<Server>));
using (var writer = new StreamWriter(filename))
{
serializer.Serialize(writer, servers);
}
使用XmlSerializer序列化
var serverInstances = new List<Server>(...);
XmlSerializer serializer = new XmlSerializer(typeof(List<Server>));
using (FileStream stream = new FileStream(fileFullName, FileMode.Create))
{
serializer.Serialize(stream, serverInstances);
}