XML serialization of hash table(C#3.0)

六月ゝ 毕业季﹏ 提交于 2019-12-31 01:48:19

问题


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);
                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


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/2918187/xml-serialization-of-hash-tablec3-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!