Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

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

4.60/5 (4 votes)
13 Jan 2012CPOL 14.3K  
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?

XML
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>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)