反序列化键值对列表
我有一些以下格式的 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
类有问题吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试在属性中指定元素名称:
Try specifying the element names in your attributes:
将 D Stanley 的回答与这篇文章,我能够想出正确的结构:
Combining D Stanley's answer with this post, I was able to come up with the right structure:
Key 或
Value
的设置器="nofollow">KeyValuePair
结构。您必须更改数据类型。您可以装饰该属性,以便可以为新类型命名任何您想要的名称。There is no setter for
Key
orValue
in theKeyValuePair
struct. You'll have to change the data type. You can decorate the property so you can name the new type whatever you want.