I have a Dictionary object which needs to be written into an XML file. The dictionary contains String type as Key and a custom class\'s Object (Deriving from System.Windows.
I used DataContractSerializer
from System.Runtime.Serialization.dll
. Serialized/deserialized my class with two Dictionary properties without any questions.
Guys.. With a little help on web I found a solution..
I had to add another class
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>: Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}
Then used the SerializableDictionary object instead of normal Dictionary. Also in my CommonControls class I had to implement "IXmlSerializable" with following methods.
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
public void WriteXml(XmlWriter writer)
{
throw new NotImplementedException();
}
#endregion
Now the whole thing is working ok. Thanks Everyone. !!!
I think you'll find that Dictionary
cannot be serialized with XmlSerializer
Generic dictionaries cannot be XmlSerialized. The error you get is caused by the public property DicCtrl
.
[XmlIgnore]
attribute to skip this property when serializing (which is probably not what you want).List<T>
BTW the [Serializable]
attribute is only needed for binary serialization. You do not need it for Xml serialization.