First of all, starting with C # 2.0, you can use a secure version like the very old Hashtable that ships with .NET 1.0. That way you can use Dictionary<DateTime, int> .
Starting with .NET 3.0, you can use the DataContractSerializer . This way you can rewrite the code as shown below.
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 that you define as follows:
[CollectionDataContract (Name = "AllMyHashtable", ItemName = "MyEntry", KeyName = "MyDate", ValueName = "MyValue")] public class MyHashtable : Dictionary<DateTime, int> { } 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 creates a C: \ output.xml file with the following:
<?xml version="1.0" encoding="utf-8"?> <AllMyHashtable xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/DataContractXmlSerializer"> <MyEntry> <MyDate>2010-06-09T22:30:00.9474539+02:00</MyDate> <MyValue>0</MyValue> </MyEntry> <MyEntry> <MyDate>2010-06-10T22:30:00.9474539+02:00</MyDate> <MyValue>1</MyValue> </MyEntry> </AllMyHashtable>
So, as we can see all the element names of the XML destination files that we can freely define.
source share