Reputation: 39
ı am working on a small c# project at visual studio 2010 and ı was trying to serialize an arraylist which has my object of People class. here is my code block
FileStream fs = new FileStream("fs.xml", FileMode.OpenOrCreate, FileAccess.Write);
XmlSerializer xml = new XmlSerializer(typeof(ArrayList));
xml.Serialize(fs,this.array);
and I have an error message at last line that is "There was an error generating the XML document." can anyone help me put please?
Upvotes: 2
Views: 9600
Reputation: 1038810
The reason you are getting this error is because you are using an ArrayList
and the XmlSerializer doesn't know about your Person
class. One possibility is to indicate to the serializer as a known type when instantiating the serializer:
var serializer = new XmlSerializer(typeof(ArrayList), new Type[] { typeof(Person) });
but a better way is to use a generic List<T>
instead of ArrayList. So let's suppose that you have the following model:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Now you could have a list of people:
List<Person> people = new List<Person>();
people.Add(new Person { FirstName = "John", LastName = "Smith" });
people.Add(new Person { FirstName = "John 2", LastName = "Smith 2" });
that you could serialize:
using (var writer = XmlWriter.Create("fs.xml"))
{
var serializer = new XmlSerializer(typeof(List<Person>));
serializer.Serialize(writer, people);
}
Upvotes: 2