序列化的键/值对XML列表 [英] Serializing a list of Key/Value pairs to XML

查看:266
本文介绍了序列化的键/值对XML列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有键/值对的列表,我想存入并从XML文件中检索。所以此任务是相似的描述<一个href="http://stackoverflow.com/questions/284858/simplest-possible-key-value-pair-file-parsing-in-net">here.我想按照标记答案的意见(使用 KeyValuePair <​​/ STRONG>和的XmlSerializer ),但我不明白这一点的工作。

I have a list of key/value pairs I'd like to store in and retrieve from a XML file. So this task is similar as described here. I am trying to follow the advice in the marked answer (using a KeyValuePair and a XmlSerializer) but I don't get it working.

我有这么远是一个设置级...

What I have so far is a "Settings" class ...

public class Settings
{
    public int simpleValue;
    public List<KeyValuePair<string, int>> list;
}

...这个类的一个实例...

... an instance of this class ...

Settings aSettings = new Settings();

aSettings.simpleValue = 2;

aSettings.list = new List<KeyValuePair<string, int>>();
aSettings.list.Add(new KeyValuePair<string, int>("m1", 1));
aSettings.list.Add(new KeyValuePair<string, int>("m2", 2));

...和下​​面的code编写实例XML文件:

... and the following code to write that instance to a XML file:

XmlSerializer serializer = new XmlSerializer(typeof(Settings));
TextWriter writer = new StreamWriter("c:\\testfile.xml");
serializer.Serialize(writer, aSettings);
writer.Close();

生成的文件是:

<?xml version="1.0" encoding="utf-8"?>
<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <simpleValue>2</simpleValue>
  <list>
    <KeyValuePairOfStringInt32 />
    <KeyValuePairOfStringInt32 />
  </list>
</Settings>

因此​​,不管是重点也不在我的列表中的对值存储,虽然元素的数量是正确的。显然,我做的事情基本上是错误的。我的问题是:

So neither key nor value of the pairs in my list are stored though the number of elements is correct. Obviously I am doing something basically wrong. My questions are:

  • 如何在文件中存储键/值对列表?
  • 如何更改默认生成的名称KeyValuePairOfStringInt32一些其他的名字,如listElement,在列表中的元素我想有?

推荐答案

KeyValuePair不是可序列化,因为它的只读属性。 这里是详细信息(感谢Thomas Levesque的)。 对于更改生成的名称使用 [XmlType将] 属性。

KeyValuePair is not serializable, because it has read-only properties. Here is more information(thanks to Thomas Levesque). For changing the generated name use the [XmlType] attribute.

定义你自己是这样的:

[Serializable]
[XmlType(TypeName="WhateverNameYouLike")]
public struct KeyValuePair<K, V>
{
  public K Key 
  { get; set; }

  public V Value 
  { get; set; }
}

这篇关于序列化的键/值对XML列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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