0

I have a XML snippet that looks like this:

<object>
  <field name="p1">Foo</field>
  <field name="p2">Bar</field>
  <field_list name="p3">
    <field_value>Me</field_value>
    <field_value>Myself</field_value>
    <field_value>I</field_value>
  </field_list>
</object>

What I would like to do is represent this in C# as a Dictionary - the keys are the names (p1, p2, p3) and the values are a List of strings - the first two (p1, p2) would have a single element and the third (p3) would have three elements.

This Xml document needs to be de-serialized. How can I do this and end up with the object desired?

Adrian Hall
  • 7,990
  • 1
  • 18
  • 26
  • Dictionary doesn't allow for re-use of the same key (i.e. key "p3" can only show up once), so you'd have to define it as Dictionary (or some variation of IEnumerable) in order to support your data. And given that Dictionary isn't natively serializable (as @akton lays out nicely below) I'm not sure it's your best choice. – Mike Parkhill Oct 01 '12 at 01:50
  • 1
    A NameValueCollection would allow for duplicate key values, but I think it has similar serialization issues to Dictionary. – Mike Parkhill Oct 01 '12 at 01:52

1 Answers1

1

The XmlSerializer class does not serialize Dictionary natively. However, there are third party serializers available such as sharp serializer and one from Peter Welter.

If you want to implement it yourself without additional libraries, implement IXmlSerializable and provide custom implementations of ReadXml and WriteXml.

See also:

Community
  • 1
  • 1
akton
  • 14,148
  • 3
  • 43
  • 47