使用XmlSerializer列表反序列化为字典

时间:2010-06-26 12:48:38

标签: c# xml

我通过将Dictionary转换为List来将数据序列化为xml 序列化没问题。

是否可以在反序列化时填充字典? (现在我在反序列化完成后填充字典并返回列表)

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

    }

代码:

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

1 个答案:

答案 0 :(得分:4)

如果问题是“我可以在不编写代码的情况下将序列化列表转换为字典”,那么答案就是否定。你现在在做什么没有太大的错误。

您可以考虑支持XML序列化的字典,这样您就不必先将其转换为列表。这是一个:

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