我有以下格式的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
类有问题? 最佳答案
尝试在属性中指定元素名称:
[XmlArray("Values")]
[XmlArrayItem("KeyValuePair")]
public List<KeyValuePair<string, string>> Values { get; set; }