Serialize Collection of Object in C#
// August 14th, 2009 // Programming
Today i’ve create a simple project… finally I find way to serialize collection of object in C#.
As luck would have it, most of the types found within the System.Collections and System.Collections.Generic namespaces have already been marked as [Serializable]. Therefore, if you wish to persist a set of objects, simply add the set to the container (such as an ArrayList or a List
first we can create a simple SoundData class like this :
[Serializable]
public class SoundData
{
private int soundId;
private string soundName;
public int SoundId
{
get { return soundId; }
set { soundId = value; }
}
public string SoundName
{
get { return soundName; }
set { soundName = value; }
}
//You will get error if you miss this constructor ^_^
public SoundData()
{ }
public SoundData(int soundId, string soundName)
{
this.soundId = soundId;
this.soundName = soundName;
}
}
Then we make new collection class that use SoundData class as item :
[Serializable]
public class ListSoundData : Collection
{
private SoundData sound;
public SoundData Sound
{
get { return sound; }
set { sound = value; }
}
public ListSoundData()
{ }
public ListSoundData(SoundData sound)
{
this.sound = sound;
}
}
Now you can add this code to Serialize and Deserialize code :
[Serializable,
XmlRoot(Namespace = "http://wcode.net")]
public class SoundMainData
{
private int lastId;
private ListSoundData listOfSound = new ListSoundData();
public int LastId
{
get { return lastId; }
set { lastId = value; }
}
public ListSoundData ListOfSound
{
get { return listOfSound; }
set { listOfSound = value;}
}
public int Add(string soundName)
{
lastId++;
SoundData sData = new SoundData(lastId, soundName);
this.ListOfSound.Add(sData);
return lastId;
}
public void Save()
{
Stream stream = File.Create("result.xml");
XmlSerializer serializer = new XmlSerializer(typeof(SoundMainData),
new Type[] { typeof(ListSoundData), typeof(SoundData) });
serializer.Serialize(stream, this);
stream.Close();
}
public void Load()
{
this.ListOfSound.Clear();
Stream stream = new FileStream("result.xml",
FileMode.Open, FileAccess.Read, FileShare.Read);
XmlSerializer serializer = new XmlSerializer(typeof(SoundMainData));
SoundMainData data = (SoundMainData)serializer.Deserialize(stream);
foreach (SoundData sound in data.ListOfSound)
{
this.ListOfSound.Add(sound);
}
this.LastId = data.LastId;
}
}
If you add SoundData in ListSoundData than Serialize it with this code:
SoundMainData data = new SoundMainData();
data.Add("willy");
data.Add("achmat");
data.Save();
Than you will have an result.xml file that contains this code :
2 1 willy 2 achmat
by : Willy Achmat Fauzi




Very shorts, simple and easy to understand, bet some more comments from your side would be great
Wow am I literally the only reply to your awesome writing?!?