65.9K
CodeProject is changing. Read more.
Home

XmlSerializer doesn't work with Dictionaries. Oh, and it has problems with KeyValuePairs too.

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (4 votes)

Jan 13, 2012

CPOL
viewsIcon

14261

Why not use the DataContractSerializer instead?Dictionary dict = new Dictionary();dict.Add("myKey", "myValue");MemoryStream memoryStream = new MemoryStream();DataContractSerializer serializer = new...

Why not use the DataContractSerializer instead?
Dictionary<string, string> dict = new Dictionary<string,string>();
dict.Add("myKey", "myValue");

MemoryStream memoryStream = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(dict.GetType());
serializer.WriteObject(memoryStream, dict);

memoryStream.Position = 0;
StreamReader reader = new StreamReader(memoryStream);
string str = reader.ReadToEnd();
str will look like
<ArrayOfKeyValueOfstringstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<KeyValueOfstringstring>
<Key>myKey</Key>
<Value>myValue</Value>
</KeyValueOfstringstring>
</ArrayOfKeyValueOfstringstring>