开发者

XML serialization of hash table(C#3.0)

开发者 https://www.devze.com 2023-01-01 00:13 出处:网络
Hi I am trying to serialize a hash table but not happening private void Form1_Load(object sender, EventArgs e)

Hi I am trying to serialize a hash table but not happening

private void Form1_Load(object sender, EventArgs e)
        {
            Hashtable ht = new Hashtable();        

            DateTime dt = DateTime.Now;
            for (int i = 0; i < 10; i++)
                ht.Add(dt.AddDays(i), i);           
            SerializeToXmlAsFile(typeof(Hashtable), ht);
        }

private void SerializeToXmlAsFile(Type targetType, Object targetObject)
        {
            try
            {
                string fileName = @"C:\output.xml";
                //Serialize to XML
                XmlSerializer s = new XmlSerializer(targetType);
                TextWriter w = new StreamWriter(fileName);
                s.Serialize(w, targetObject);
            开发者_StackOverflow    w.Flush();
                w.Close();
            }
            catch (Exception ex) { throw ex; }
        }

After a google search , I found that objects that impelment IDictonary cannot be serialized. However, I got success with binary serialization.

But I want to have xml one. Is there any way of doing so?

I am using C#3.0

Thanks


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<DateTime, int>.

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<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 produce C:\output.xml file with the following contain:

<?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 how we can see all names of the elements of the destination XML files we can free define.


You can create your own Hashtable derived from standart Hashtable with implementation of IXmlSerializable. So you will implmenent ReadXml(XmlReader reader) & WriteXml(XmlWriter writer) where you can put your own logic on how to read and write values from your Hashtablw with given XmlReader & XmlWriter.


I suggest you use DataContractSerializer, it's more powerful and easier to use.

0

精彩评论

暂无评论...
验证码 换一张
取 消