反序列化KeyValuePairs列表

时间:2012-02-06 19:16:16

标签: c# xml-serialization

我有以下格式的XML:

<ObjectData>
  <ModelName>MODEL_123</ModelName>
  <ObjectName>OBJECT_A</ObjectName>
  <Values>
    <KeyValuePair>
      <Key>NAME</Key>
      <Value>PAUL</Value>
    </KeyValuePair>
    ...
  </Values>
</ObjectData>
...

我想将其反序列化为以下类:

[XmlRoot(Namespace = "")]
public class ObjectData
{
    [XmlElement(Namespace = "")]
    public string ModelName { get; set; }
    [XmlElement(Namespace = "")]
    public string ObjectName { get; set; }
    [XmlArray]
    public List<KeyValuePair<string, string>> Values { get; set; }
}

当我使用此代码时,KeyValuePair未被反序列化,而且Values属性为空。

List<ObjectData> data = new List<ObjectData>();
XmlSerializer serializer = new XmlSerializer(typeof(ObjectData));

using (XmlReader reader = XmlReader.Create(new StringReader(inputXML)))
{             
    reader.MoveToContent();
    ObjectData temp = (ObjectData)serializer.Deserialize(reader);
    data.Add(temp);
}  

KeyValuePair类是否在我使用它的方式中不可序列化?或者我的ObjectData班级有问题吗?

3 个答案:

答案 0 :(得分:3)

尝试在属性中指定元素名称:

[XmlArray("Values")]
[XmlArrayItem("KeyValuePair")]
public List<KeyValuePair<string, string>> Values { get; set; }

答案 1 :(得分:2)

将D Stanley的答案与this post结合起来,我能够提出正确的结构:

[XmlRoot(Namespace = "")]
public class ObjectData
{
    [XmlElement(Namespace = "")]
    public string ModelName { get; set; }
    [XmlElement(Namespace = "")]
    public string ObjectName { get; set; }
    [XmlArray("Values")]
    [XmlArrayItem("KeyValuePair")] 
    public List<KeyValuePair<string, string>> Values { get; set; }
}

[Serializable]
public class KeyValuePair<K, V> {
    public K Key { get; set; }
    public V Value { get; set; }
    public KeyValuePair() { }
    public KeyValuePair(K key, V value)
    {
        this.Key = key;
        this.Value = value;
    }
}

答案 2 :(得分:1)

KeyValuePair struct中没有KeyValue的设定者。您必须更改数据类型。您可以装饰该属性,以便您可以随意命名新类型。

....
    [XmlArray("Values")]
    [XmlArrayItem("KeyValuePair")]  //not needed if MyItem is named KeyValuePair
    public List<MyItem> Values { get; set; }
}

public class MyItem
{
    public string Key { get; set; }
    public string Value { get; set; }
}