3

I want to convert my dictionary data into XML. I am trying to use XML serialization but I am getting an error. Below is my code.

class Program
{

    static void Main(string[] args)
    {
        Dictionary<int, AddressDetails> objDic = new Dictionary<int, AddressDetails>();
        for (int i = 1; i <= 5; i++)
        {
            AddressDetails obj = new AddressDetails();
            obj.HouseNo = i;
            obj.StreetName = "New Street One " + i;
            obj.City = "New Delhi One " + i;
            objDic.Add(i, obj);
        }

        string str = Utility.GetXMLFromObject(objDic);
    }

}

public class AddressDetails 
{
    public int HouseNo { get; set; }
    public string StreetName { get; set; }
    public string City { get; set; }
    private string PoAddress { get; set; }
}

public static class Utility
{
    public static string GetXMLFromObject(object o)
    {
        StringWriter sw = new StringWriter();
        XmlTextWriter tw = null;
        try
        {
            XmlSerializer serializer = new XmlSerializer(o.GetType());
            tw = new XmlTextWriter(sw);
            serializer.Serialize(tw, o);
        }
        catch (Exception ex)
        {
            //Handle Exception Code
        }
        finally
        {
            sw.Close();
            if (tw != null)
            {
                tw.Close();
            }
        }
        return sw.ToString();
    }
}

Error Code line : XmlSerializer serializer = new XmlSerializer(o.GetType());

Error Description :

The type System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[ConsoleApplication5.AddressDetails, ConsoleApplication5, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] is not supported because it implements IDictionary.

Please suggest.

KiddoDeveloper
  • 568
  • 2
  • 11
  • 34
  • Dictionaries can't be serialized. Please take a look at this: http://stackoverflow.com/questions/12554186/how-to-serialize-deserialize-to-dictionaryint-string-from-custom-xml-not-us – kassi Sep 19 '16 at 06:45
  • 1
    http://theburningmonk.com/2010/05/net-tips-xml-serialize-or-deserialize-dictionary-in-csharp/ – JFM Sep 19 '16 at 06:47

2 Answers2

3

Try the solutions explained in the link below:

http://theburningmonk.com/2010/05/net-tips-xml-serialize-or-deserialize-dictionary-in-csharp/

You have to either use DataContract Serialization instead of XmlSerialization or use a custom Dictionary type.

sachin
  • 2,341
  • 12
  • 24
1

Use the following dictionary extension.

[XmlRoot("Dictionary")]
public class DictionaryEx<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        XDocument document = null;
        using (XmlReader subtreeReader = reader.ReadSubtree())
        {
            document = XDocument.Load(subtreeReader);
        }

        if (document == null)
            return;

        XmlSerializer serializer = new XmlSerializer(typeof(KeyValuePairEx<TKey, TValue>));
        foreach (XElement element in document.Descendants(XName.Get("Item")))
        {
            using (XmlReader xmlReader = element.CreateReader())
            {
                var pair = serializer.Deserialize(xmlReader) as KeyValuePairEx<TKey, TValue>;
                this.Add(pair.Key, pair.Value);
            }
        }

        reader.ReadEndElement();
    }

    public void WriteXml(XmlWriter writer)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(KeyValuePairEx<TKey, TValue>));
        XmlSerializerNamespaces xmlNameSpaces = new XmlSerializerNamespaces();
        xmlNameSpaces.Add(string.Empty, string.Empty);

        foreach (TKey key in this.Keys)
        {
            TValue value = this[key];
            var pair = new KeyValuePairEx<TKey, TValue>(key, value);
            serializer.Serialize(writer, pair, xmlNameSpaces);
        }
    }

    [XmlRoot("Item")]
    public class KeyValuePairEx<TKey, TValue>
    {
        [XmlAttribute("Key")]
        public TKey Key;

        [XmlAttribute("Value")]
        public TValue Value;

        public KeyValuePairEx()
        {
        }

        public KeyValuePairEx(TKey key, TValue value)
        {
            Key = key;
            Value = value;
        }
    }
}

The above code is from Keyo

Community
  • 1
  • 1