Hi, I'm pretty new to C# and am trying to write a class with data in it that i can save and load from an XML file, are there any built in Generic Containers/Collection, something like List or Stack that XML can serialize, my code is below, but whatever container i use i get an exception complaining about how it can't serialize the collection i am using (List) in this case.
How do i have to go about serializing a collection of objects Is it something that can be done with a similar amoutn of code as below or am i dreaming
namespace Test
{
public class ClassA
{
public List<ClassB> Events;
public ClassA()
{
Events = new List<ClassB>();
Events.Add(new ClassB());
}
#region Load/Save Code
public void Save(string filename)
{
Stream stream = File.Create(filename);
XmlSerializer serializer = new XmlSerializer(typeof(ClassA));
serializer.Serialize(stream, this);
stream.Close();
return;
}
public static ClassA Load(string filename)
{
Stream stream = File.OpenRead(filename);
XmlSerializer serializer = new XmlSerializer(typeof(ClassA));
ClassA result = (ClassA) serializer.Deserialize(stream);
stream.Close();
return (result);
}
#endregion
}
public class ClassB
{
public int testVar;
public ClassB()
{
testVar = 1;
return;
}
}
}

C# Newb - XMLSerializing a List
Deepthi Rao
I dont know if you understand VB.NET but here is some code I gave this member a while back, includes serializing/deserializing in the OP question
http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=739419&SiteID=1
What errors are you getting
try these:
http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.serialize.aspx
http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx
I believe from your code, it should not be:
serializer.Serialize(stream, this);but should be:
serializer.Serialize(stream, this.Events);
you *may* also need to give the Serializer additional types since it appears you are storing different classes in the List<T>() collection. Try the above and see how it goes.
Corby111
Sumit Chawla
Pavan Podila
thanks :)
Sweeps78
glad you got it sorted out...got me confused too. Started rattling out my mind (which by the way has a cold) posting all possible problems to check/add..giving links...then a few minutes later copied and pasted the code, works fine for both deserializing and serializing...lol. Then modified the code a bit to just serialize the collection, as in your original question....
ah well, glad you got it sorted. Feel free (and would advise it) to mark any answer thats right to you - benefits others