C# 中XML序列化与反序列化学习笔记
程序员文章站
2022-06-16 08:19:32
...
static void Main(string[] args)
{
List<Person> list = new List<Person>();
for (int i = 0; i < 30; i++)
{
Person p = new Person();
p.Name = "大爷" + i;
p.Age = i + 20;
p.Gender = (char)i;
list.Add(p);
}
// Person[] pLIst = list.ToArray();
// XmlSerializer xml2 = new XmlSerializer(typeof(Person[]));
XmlSerializer xml = new XmlSerializer(typeof(List<Person>) );//注意此处的typeof
using (FileStream fsW=new FileStream("person.xml",FileMode.Create,FileAccess.Write))
{
xml.Serialize(fsW,list);
}
using (FileStream fsR=new FileStream("person.xml",FileMode.Open,FileAccess.Read))
{
//Person[] p=(Person[])xml2.Deserialize(fsR);
List<Person> p2 = (List<Person>)xml.Deserialize(fsR); //此处的强转类型应当与xml设置的类型一致,否则会报错
}
}
//上述两种方法本质上是一样的,因为生成的XML文档完全相同
转载于:https://my.oschina.net/u/1182881/blog/423153