.net 将键/值对列表序列化为 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2658916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Serializing a list of Key/Value pairs to XML
提问by Slauma
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 KeyValuePairand a XmlSerializer) but I don't get it working.
我有一个键/值对列表,我想在 XML 文件中存储和检索。因此,此任务与此处描述的相似。我试图遵循标记答案中的建议(使用KeyValuePair和XmlSerializer),但我没有让它工作。
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));
... and the following code to write that instance to a XML file:
...以及以下代码将该实例写入 XML 文件:
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
TextWriter writer = new StreamWriter("c:\testfile.xml");
serializer.Serialize(writer, aSettings);
writer.Close();
The resulting file is:
生成的文件是:
<?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:
因此,尽管元素数量正确,但我的列表中的对的键和值均未存储。显然我做的事情基本上是错误的。我的问题是:
- How can I store the key/value pairs of the list in the file?
- How can I change the default generated name "KeyValuePairOfStringInt32" of the elements in the list to some other name like "listElement" I'd like to have?
- 如何将列表的键/值对存储在文件中?
- 如何将列表中元素的默认生成名称“KeyValuePairOfStringInt32”更改为我想要的其他名称,例如“listElement”?
回答by Petar Minchev
KeyValuePair is not serializable, because it has read-only properties. Hereis more information(thanks to Thomas Levesque).
For changing the generated name use the [XmlType]attribute.
KeyValuePair 不可序列化,因为它具有只读属性。这是更多信息(感谢 Thomas Levesque)。要更改生成的名称,请使用该[XmlType]属性。
Define your own like this:
像这样定义你自己的:
[Serializable]
[XmlType(TypeName="WhateverNameYouLike")]
public struct KeyValuePair<K, V>
{
public K Key
{ get; set; }
public V Value
{ get; set; }
}

