您收到此错误的原因是因为您使用的是 anArrayList
并且 XmlSerializer 不知道您的Person
类。一种可能性是在实例化序列化器时将序列化器指示为已知类型:
var serializer = new XmlSerializer(typeof(ArrayList), new Type[] { typeof(Person) });
但更好的方法是使用泛型List<T>
而不是 ArrayList。因此,假设您有以下模型:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
现在你可以有一个人员列表:
List<Person> people = new List<Person>();
people.Add(new Person { FirstName = "John", LastName = "Smith" });
people.Add(new Person { FirstName = "John 2", LastName = "Smith 2" });
你可以序列化:
using (var writer = XmlWriter.Create("fs.xml"))
{
var serializer = new XmlSerializer(typeof(List<Person>));
serializer.Serialize(writer, people);
}