Is it possible to Deserialize the following piece of XML into a Dictionary<int,string> object?
XML:
<Config>
<DatabaseConnections>
<Connection Name="Source Connection" Value="ConnectionStringValue" />
<Connection Name="Target Connection" Value="ConnectionStringValue" />
<DatabaseConnections>
<Config>
I have a class which will have a property of Dictionary<int,string> {get;set;}
I would like to use the following C# code to do this:
XmlSerializer xs = new XmlSerializer(typeof(Config));
using(StringReader sr = new StringReader(rootnode.OuterXml))
{
return (Config)xs.Deserialize(sr);
}
Are there any alternatives to doing this?
You cannot use the default
XmlSerializerimplementation to (de)serializeIDictionaryobjects to Xml. From the MSDNXmlSerializerdocumentation:The
Dictionary<>class implements both interfaces, but does not have anAddmethod that takes a single parameter, so it fails.More to the point, the xml serialization code explicitly disallows classes that implement
IDictionary(from Reflector, looking atTypeScope.GetDefaultIndexer):So you can’t even make the work by subclassing
Dictionary<>and adding the requiredAddoverload.The article Generic Dictionaries vs. the XmlSerializer describes one workaround: