简体   繁体   中英

Deserializing with XmlSerializer List into Dictionary

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 I populate dictionary after deserialization completes and list is returned )

 [Serializable]
    public class Attribute
    {
        public string Key { get; set; }
        public int Value1 { get; set; }
        public int Value2 { get; set; }
        public int Value3 { get; set; }


        public Attribute() { }
        public Attribute(string key, int value1, int value2, int value3)
        {
            Key = key;
            Value1 = value1;
            Value2 = value2;
            Value3 = value3;
        }
    }

    [XmlRoot("Container")]    
    public class TestObject
    {
        public TestObject() { }
        private Dictionary<string, Attribute> dictionary = new Dictionary<string, Attribute>();


        [XmlIgnore()]
        public Dictionary<string, Attribute> Dictionary
        {
            set { dictionary = value; }
            get { return dictionary; }
        }

        public string Str { get; set; }        


        private List<Attribute> _attributes = new List<Attribute>();       
        public List<Attribute> Attributes
        {
            get 
            {
                if (Dictionary.Count>0)
                {

                    foreach (string key in Dictionary.Keys)
                    {
                        _attributes.Add(new Attribute(key, Dictionary[key].Value1,  Dictionary[key].Value2,    Dictionary[key].Value3));
                    }
                    return _attributes;
                }
            return _attributes;
            }               
        }

    }

Code:

 TestObject TestObj = new TestObject();
 TestObj.Dictionary.Add("asdsad", new Attribute { Value1 = 232, Value2 = 12, Value3 = 89 });
 TestObj.Dictionary.Add("sdfer", new Attribute { Value1 = 10, Value2 = 7, Value3 = 857 });
 TestObj.Dictionary.Add("zxcdf", new Attribute { Value1 = 266, Value2 = 85, Value3 = 11 });                           

 TestObj.Str = "Test";            

 XmlWriterSettings settings = new XmlWriterSettings();
 settings.OmitXmlDeclaration = true;
 settings.Indent = true;
 XmlSerializer serializer = new XmlSerializer(typeof(TestObject));

 using (XmlWriter writer = XmlWriter.Create(@"C:\test.xml", settings))
 {              
      XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
      namespaces.Add(string.Empty, string.Empty);

      serializer.Serialize(writer, TestObj, namespaces);                            
 }

 TestObject newob;
 using (TextReader textReader = new StreamReader(@"C:\test.xml"))
 {
      newob = (TestObject)serializer.Deserialize(textReader);
     //repopulate dictionary from Attribute list
      foreach (Attribute atr in newob.Attributes)
      {
          //code
      }
 }

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);
    }
  }

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