This is my class structure:
class DataItem
{
public string Id { get; set; }
public string Type { get; set; }
private Dictionary
Unfortunately, generic dictionaries are not xml serializable.
The workaround is to greate a separate field specifically to support serialization that exposes the elements of the dictionary as a list of key/value pairs. You then also have to mark the dictionary member with the XmlIgnore
attribute.
Alternatively, you can use something other than XmlSerializer (like DataContractSerializer) which does support dictionary types.
Here's a link to an article which provides a good example of how modify your type to support XML Serialization with a dictionary.
One important point if you use this code - the serialized items may appear in arbitrary order in the output. This is a consequence of using dictinoaries (which are unordered) as the storage model for your data.
[XmlIgnore()]
public Dictionary Properties
{
set { properties = value; }
get { return properties ; }
}
[XmlArray("Stuff")]
[XmlArrayItem("StuffLine", Type=typeof(DictionaryEntry))]
public DictionaryEntry[] PropertiesList
{
get
{
//Make an array of DictionaryEntries to return
DictionaryEntry[] ret=new DictionaryEntry[Properties.Count];
int i=0;
DictionaryEntry de;
//Iterate through Stuff to load items into the array.
foreach (KeyValuePair props in Properties)
{
de = new DictionaryEntry();
de.Key = props.Key;
de.Value = props.Value;
ret[i]=de;
i++;
}
return ret;
}
set
{
Properties.Clear();
for (int i=0; i