Generic Dictionary not serializing with the rest of a class...

G

Guest

I have the following classes defined (gets/sets removed for brevity):

[Serializable]
public class Warband
{
public Warband()
{
Contents = new Dictionary<string, WarbandContent>();
}

[XmlElement(ElementName = "Name")]
private string _Name;

[XmlElement(ElementName = "Alignment")]
private string _Alignment;

[XmlElement(ElementName = "BuildTotal")]
private ushort _BuildTotal;

[XmlElement(ElementName = "Activations")]
private ushort _Activations;

[XmlElement(ElementName = "Comments")]
private string _Comments;

[XmlArray(ElementName = "Contents")]
private Dictionary<string, WarbandContent> _Contents;

public void Serialize(string FileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(Warband));
TextWriter writer = new StreamWriter(FileName);

serializer.Serialize(writer, this);
writer.Close();
}
}

[Serializable]
class WarbandContent
{
[XmlElement(ElementName = "MiniatureID")]
private string _MiniatureID;

[XmlElement(ElementName = "Quantity")]
private uint _Quantity;

[XmlElement(ElementName = "Cost")]
private uint _Cost;

[XmlElement(ElementName = "IsCommander")]
private bool _IsCommander;
}

When I call the Serialize method of a Warband object, all properties of that
object are written to the Xml, with the exception of the Dictionary property.
Is there a way to get this Dictionary written to the Xml, or should I start
looking for another way to do this?

Gabe
 
F

Frank Dzaebel

Hello Gabe,
When I call the Serialize method of a Warband object, all properties of that
object are written to the Xml, with the exception of the Dictionary property.
Is there a way to get this Dictionary written to the Xml, or should I start
looking for another way to do this?

Unfortunately there's no way to make XmlSerializer function with
IDictionary-derived objects since the infrastructure explicitly checks for
IDictionary at run time and disables serialization.
But there are some ways around this. One is that you can implement an interface
called IXmlSerializable for the object, but there are also other ways:

http://msdn.microsoft.com/msdnmag/issues/03/06/XMLFiles/
(search for "dictionary") [.NET 1.1]

http://blogs.metapropeller.com/klisa/PermaLink,guid,f70867c4-59a3-4a2b-b104-032b960c339d.aspx

http://babelfish.altavista.com/babe...peur.org/crazyht/archive/2005/04/25/6320.aspx


ciao Frank
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top