Hi I am trying to serialize a hash table but not happening
private void Form1_Load(object sender, EventArgs e)
{
Hashtable ht = new Hashtable
First of all starting with C# 2.0 you can use type safe version of very old Hashtable
which come from .NET 1.0. So you can use Dictionary
.
Starting with .NET 3.0 you can use DataContractSerializer
. So you can rewrite you code like following
private void Form1_Load(object sender, EventArgs e)
{
MyHashtable ht = new MyHashtable();
DateTime dt = DateTime.Now;
for (int i = 0; i < 10; i++)
ht.Add(dt.AddDays(i), i);
SerializeToXmlAsFile(typeof(Hashtable), ht);
}
where SerializeToXmlAsFile
and MyHashtable
type you define like following:
[CollectionDataContract (Name = "AllMyHashtable", ItemName = "MyEntry",
KeyName = "MyDate", ValueName = "MyValue")]
public class MyHashtable : Dictionary { }
private void SerializeToXmlAsFile(Type targetType, Object targetObject)
{
try {
string fileName = @"C:\output.xml";
DataContractSerializer s = new DataContractSerializer (targetType);
XmlWriterSettings settings = new XmlWriterSettings ();
settings.Indent = true;
settings.IndentChars = (" ");
using (XmlWriter w = XmlWriter.Create (fileName, settings)) {
s.WriteObject (w, targetObject);
w.Flush ();
}
}
catch (Exception ex) { throw ex; }
}
This code produce C:\output.xml file with the following contain:
2010-06-09T22:30:00.9474539+02:00
0
2010-06-10T22:30:00.9474539+02:00
1
So how we can see all names of the elements of the destination XML files we can free define.