与XmlSerializer的名单将反序列化词典 [英] Deserializing with XmlSerializer List into Dictionary

查看:123
本文介绍了与XmlSerializer的名单将反序列化词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被转换成词典序列列出数据转换成XML。结果
序列化是确定的。



是填充在反序列化可能词典? (我现在填充字典反序列化完成后,返回列表)

  [Serializable接口] 
公共类属性
{
公共字符串键{获得;组; }
公众诠释值1 {搞定;组; }
公众诠释值2 {搞定;组; }
公众诠释值3 {搞定;组; }


公共属性(){}
公共属性(字符串键,INT值1,INT值2,INT VALUE3)
{
键=键;
值1 =值;
值2 =值2;
值3 =值3;
}
}

[XmlRoot(容器)]
公共类的TestObject
{
公众的TestObject(){}
私人字典<字符串,属性和GT;词典=新词典<字符串,属性及GT;();


[XmlIgnore()]
公众解释<字符串,属性和GT;字典
{
集合{字典=价值; }
{返回字典; }
}

公共字符串str {搞定;组; }


私人列表<属性与GT; _attributes =新的List<属性与GT;();
公开名单<属性与GT;属性
{
得到
{
如果(Dictionary.Count大于0)
{

的foreach(在Dictionary.Keys字符串键)
{
_attributes.Add(新属性(键,字典[关键] .Value1,字典[关键] .Value2,字典[关键] .Value3));
}
返回_attributes;
}
返回_attributes;
}
}

}



代码:

 的TestObject TestObj =新的TestObject(); 
TestObj.Dictionary.Add(asdsad,新的属性{值1 = 232,值2 = 12,值3 = 89});
TestObj.Dictionary.Add(sdfer,新的属性{值1 = 10,值2 = 7,值3 = 857});
TestObj.Dictionary.Add(zxcdf,新的属性{值1 = 266,值2 = 85,值3 = 11});

TestObj.Str =测试;

XmlWriterSettings设置=新XmlWriterSettings();
settings.OmitXmlDeclaration = TRUE;
settings.Indent = TRUE;
XmlSerializer的序列化=新的XmlSerializer(typeof运算(的TestObject));使用(XmlWriter的作家= XmlWriter.Create(@C:\test.xml设置))


{
XmlSerializerNamespaces命名空间=新XmlSerializerNamespaces();
namespaces.Add(的String.Empty,的String.Empty);

serializer.Serialize(作家,TestObj,命名空间);
}

的TestObject newob;使用(C:\test.xml的TextReader的TextReader =新的StreamReader(@))

{
newob =(的TestObject)serializer.Deserialize(TextReader的);
//重新填充从属性列表
的foreach(ATR的属​​性在newob.Attributes)
{
//代码
}
}
字典


解决方案

如果问题是我可以一个序列化的列表转换为一个字典没有编写代码,那么答案是否定的。没有太多的毛病你现在正在做什么。



您可以考虑支持XML序列化的字典,所以你不必先将其转换成一个列表。这里有一个:

 公共类XmlDictionary< T,V> :字典< T,V>中的IXmlSerializable {
[XmlType将(入口)]
公共结构进入{
公共入口(T键,V值):这个(){键=键;值=价值; }
[的XmlElement(钥匙)]
公共T键{搞定;组; }
[的XmlElement(值)]
公共V值{搞定;组; }
}

System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema(){
返回NULL;
}

无效IXmlSerializable.ReadXml(System.Xml.XmlReader读者){
this.Clear();
无功序列化=新的XmlSerializer(typeof运算(列表<钥匙进入GT;));
reader.Read();
变种名单=(列表<钥匙进入GT;)serializer.Deserialize(读卡器);
的foreach(列表中的条目VAR)this.Add(entry.Key,entry.Value);
reader.ReadEndElement();
}

无效IXmlSerializable.WriteXml(System.Xml.XmlWriter作家){
无功名单=新名单,LT;进入>(this.Count);
的foreach(在此VAR​​的条目)list.Add(新条目(entry.Key,entry.Value));
XmlSerializer的序列化=新的XmlSerializer(list.GetType());
serializer.Serialize(作家,清单);
}
}


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

这篇关于与XmlSerializer的名单将反序列化词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆