Deserializing with XmlSerializer List into Dictionary

前端 未结 1 551
陌清茗
陌清茗 2021-01-07 02:34

I am serializing data into xml by converting Dictionary into List.
The serialization is ok.

Is it possible to populate dictionary on deserialization? (right now

相关标签:
1条回答
  • 2021-01-07 03:15

    If the question is "can I convert a serialized list to a dictionary without writing code" then the answer is no. There isn't much wrong with what you are doing now.

    You could consider a dictionary that supports XML serialization so you don't have to convert it to a list first. Here's one:

      public class XmlDictionary<T, V> : Dictionary<T, V>, IXmlSerializable {
        [XmlType("Entry")]
        public struct Entry {
          public Entry(T key, V value) : this() { Key = key; Value = value; }
          [XmlElement("Key")]
          public T Key { get; set; }
          [XmlElement("Value")]
          public V Value { get; set; }
        }
    
        System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() {
          return null;
        }
    
        void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) {
          this.Clear();
          var serializer = new XmlSerializer(typeof(List<Entry>));
          reader.Read();
          var list = (List<Entry>)serializer.Deserialize(reader);
          foreach (var entry in list) this.Add(entry.Key, entry.Value);
          reader.ReadEndElement();
        }
    
        void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) {
          var list = new List<Entry>(this.Count);
          foreach (var entry in this) list.Add(new Entry(entry.Key, entry.Value));
          XmlSerializer serializer = new XmlSerializer(list.GetType());
          serializer.Serialize(writer, list);
        }
      }
    
    0 讨论(0)
提交回复
热议问题