开发者

XML Serializing a class with a Dictionary<string, List<string>> object

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.WriteAttribute开发者_高级运维String("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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜