views:

40

answers:

1

Is it possible to implement IXmlSerializable and in my XML file capture an object of type Dictionary> ?

I have the following

public class coolio : IXmlSerializable
{
private int a;
private bool b;
private string c;
private Dictionary<string, List<string>> coco;

public coolio(int _a, bool _b, string _c, Dictionary<string, List<string>> _coco)
    {
    a=_a;
    b=_b;
    c=_c;
    coco=_coco;
    }

public System.Xml.Schema.XmlSchema GetSchema()
    {
    return null;
    }

public void WriteXml(XmlWriter writer)
    {
    const string myType = "coolio";
    writer.WriteStartElement(myType);
    writer.WriteAttributeString("a", a.ToString());
    writer.WriteAttributeString("b", b.ToString());
    writer.WriteAttributeString("c", c);

    // How do I add a subelement for Dictionary<string, List<string>> coco?

    writer.WriteEndElement();
    }

public void ReadXml(XmlReader reader)
    {
    if (reader.MoveToContent() != XmlNodeType.Element || reader.LocalName != "coolio") 
                return;
    a= int.Parse(reader["a"]);
    b = bool.Parse(reader["b"]);
    c= reader["c"];

    // How do I read subelement into Dictionary<string, List<string>> coco?
    }
}

But I am stumped as to how I could add the Dictionary> (XML seriliazed to my XML file)

+1  A: 
writer.WriteStartElement("CocoKeys");
foreach (var kvp in coco)
{
  writer.WriteStartElement("CocoKey");
  writer.WriteAttributeString("key", kvp.Key);
  writer.WriteStartElement("CoCoValues");
  foreach(string s in kvp.Value)
  {
    writer.WriteStartElement("CoCoValue");
    writer.WriteString(s);
    writer.WriteEndElement();
  }
  writer.WriteEndElement();
  writer.WriteEndElement();
  writer.WriteEndElement();
}

This should produce something like this:

<CocoKeys>
  <CocoKey key="sample">
  <CocoValues>
    <CocoValue>Sample1</CocoValue>
    <CocoValue>Sample2</CocoValue>
    <CocoValue>Sample3</CocoValue>
  </CocoKey>
</CocoKeys>

On the other side, just iterate over it and recostruct it. I hope the code is correct, I did it just by your example. You might have to adjust method calls, but in pseudo it should be correct.

Femaref
Ahh, I was afraid of that -- having to iterate through, I thought there must be a better way, I guess not -- Thanks!
Matt
np, just practising on-the-fly writing.
Femaref