2011-09-20 64 views
2
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最簡單的方法;什麼是序列化和反序列化到XML

感謝您的幫助!

回答

6

使用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); 
} 
3

使用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); 
} 
+1

標記類爲'Serializable'是沒有必要的。 –

+0

不要忘記對於不想序列化的成員,有'NonSerializedAttribute'。並且'ISerializable'用於更好地控制過程。 – Skizz

+0

差不多,但是OP想要序列化'List ' – Jodrell