I need an XML-serializable dictionary. Actually, I now have two quite different programs that need one. I was rather surprised to see that .NET doesn't have one. I asked the question elsewhere and got sarcastic responses. I don't understand why it's a stupid question.
Can someone enlighten me, given how dependent various .NET features are on XML serialization, why there isn't an XML-serializable dictionary. Hopefully, you can also explain why some people consider that a daft question. I guess I must be missing something fundamental and I'm hoping you'll be able to fill in the gaps.
I know this has been done to death now, but here is my contribution. I took the good bits from the solutions from @Loudenvier and @Jack and wrote my own serialisable (sorry, I'm British) dictionary class.
I like this approach because you won't have to explicitly serialise or deserialise anything, just pump the whole class hierarchy through an XmlSerializer and you're done.
Create one of your own :-), the readonly feature is bonus but if you need a key other than a string then the class needs some modifications...
I know this has been answered before, but since I have a very concise way (code) for doing IDictionary serialization with the DataContractSerializer class (used by WCF, but could and should be used anywhere) I couldn't resist contributing it here:
This works perfectly in .NET 4 and should also work in .NET 3.5, although I didn't test it yet.
UPDATE: It doesn't work in .NET Compact Framework (not even NETCF 3.7 for Windows Phone 7) as the
DataContractSerializer
is not supported!I did the streaming to string because it was more convenient to me, although I could have introduced a lower-level serialization to Stream and then used it to serialize to strings, but I tend to generalize only when needed (just like premature optimization is evil, so it is premature generalization...)
Usage is very simple:
myDictCopy will be a verbatim copy of myDict.
You'll also notice that the generic methods provided will be able to serialize any type (to the best of my knowledge) since it is not limited to IDictionary interfaces, it can be really any generic type T.
Hope it helps someone out there!
Use the DataContractSerializer! See the sample below.
The above code produces the following xml:
This is my implementation.
The thing about XML Serialization is that it's not just about creating a stream of bytes. It's also about creating an XML Schema that this stream of bytes would validate against. There's no good way in XML Schema to represent a dictionary. The best you could do is to show that there's a unique key.
You can always create your own wrapper, for instance One Way to Serialize Dictionaries.