Click here to Skip to main content
15,896,606 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.60/5 (4 votes)
13 Jan 2012CPOL 14.1K   2
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)


Written By
Web Developer
Ireland Ireland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 very nice Pin
HoyaSaxa9313-Jan-12 7:29
HoyaSaxa9313-Jan-12 7:29 
GeneralI said there was probably a much, much nicer way to do it! :... Pin
OriginalGriff13-Jan-12 2:08
mveOriginalGriff13-Jan-12 2:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.