XML错误序列化DictionaryEntry []属性

时间:2012-03-21 23:21:07

标签: c# xml arrays xml-serialization

我收到一条消息的异常:“XML文档中存在错误”。

代码:

        private readonly SortedList<string, object> _attributes;

        [XmlArray("Attributes")] 
        [XmlArrayItem("AttributesLine", Type=typeof(DictionaryEntry))] 
        public DictionaryEntry[] _x_Attributes 
        { 
            get 
            { 
                DictionaryEntry[] ret = new DictionaryEntry[_attributes.Count]; 
                int i=0;
                foreach (KeyValuePair<string, object> stuffLine in _attributes)
                {
                    object value = stuffLine.Value;     // <--- float[]         
                    ret[i++] = new DictionaryEntry {Key = stuffLine.Key, Value = value};                
                }
                return ret; 
            }
            set
            {
                _attributes.Clear();
                foreach (DictionaryEntry entry in value)
                {
                    _attributes.Add((string) entry.Key, entry.Value);
                }
            }
        }

每个键/值对的值是float []类型。我仍然希望值类型保持为'System.Object',因为某些键可以具有除float []之外的类型的值(在任何情况下,即使字典填充了一个条目,我也会得到异常)。

编辑澄清:我正在使用'XmlSerializer',它在entry.Value是一个'浮动'时工作正常。

1 个答案:

答案 0 :(得分:0)

我假设您正在使用XMLSerializer,它无法处理Generic Dictionary对象。我已经看到自己使用词典时抛出的错误。您需要选择其中一个可以处理它们的序列化程序。

尝试使用 DataContractSerializer

相关问题