简体   繁体   中英

Handling multiple fields with one XML tag in C# XmlSerializer

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?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM