Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

c# - Serializing an ArrayList with XmlSerializer

? 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...