Can you serialize a Dictionary using XMLSerializer?

S

Shawn

Hi;
I would like to be able to use the XMLSerializer to serialize and
deserialize a dictionary. is that possible? i know that you can serialize an
object that implements the ICollection interface. does the fact that
Dictionary inherits from ICollection<> cause a problem?
Currently i am using a class that inherits from ICollection and it has a
Dictionary as it's container. but when it gets to creating the serialized
object it blows up. here is the code for the collection class:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace testBed
{
[Serializable]

public class ItemFile : ICollection
{

private Dictionary<object, Item> ADList = new Dictionary<object,
Item>();

public Item this[object key]
{
get { return (Item)ADList[key]; }
}
public void Add(Item entry)
{
ADList.Add(entry.GetProperty("ID"), entry);
}
public void Clear()
{
ADList.Clear();
}
public int Count
{
get { return ADList.Count; }
}

public void CopyTo(Array a, int index)
{
foreach(Item item in ADList.Values)
{
a.SetValue(item, index);
index++;
}
}
public object SyncRoot
{
get { return this; }
}
public bool IsSynchronized
{
get { return false; }
}
public IEnumerator GetEnumerator()
{
return ADList.GetEnumerator();
}
}
}

here is the code i use to read and write:

private static void read(string filename, out ItemFile file)
{
XmlSerializer serializer = new XmlSerializer(typeof(ItemFile));
FileStream fs = new FileStream(filename, FileMode.Open);
file = (ItemFile)serializer.Deserialize(fs);

}
private static void write(string filename, ItemFile file)
{
XmlSerializer serializer = new XmlSerializer(typeof(ItemFile));
TextWriter writer = new StreamWriter(filename);
serializer.Serialize(writer, file);
writer.Close();
}

any help would be appreciated.
thanks.
 
I

Ignacio Machin ( .NET/ C# MVP )

Hi;
I would like to be able to use the XMLSerializer to serialize and
deserialize a dictionary. is that possible?

Hi,

I think that is depends of the key/value types, if you are using a
non serializable type you will not be able to serialize it
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top