Dot-Net

將鍵/值對列表序列化為 XML

  • April 17, 2010

我有一個鍵/值對列表,我想在 XML 文件中儲存和檢索。因此,此任務與此處描述的類似。我正在嘗試遵循標記答案中的建議(使用KeyValuePairXmlSerializer),但我沒有得到它的工作。

到目前為止,我有一個“設置”類……

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

…這個類的一個實例…

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));

…以及將該實例寫入 XML 文件的以下程式碼:

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>

因此,儘管元素的數量是正確的,但我的列表中的對的鍵和值都沒有儲存。顯然我做的事情基本上是錯誤的。我的問題是:

  • 如何將列表的鍵/值對儲存在文件中?
  • 如何將列表中元素的預設生成名稱“KeyValuePairOfStringInt32”更改為我想要的其他名稱,例如“listElement”?

KeyValuePair 不可序列化,因為它具有隻讀屬性。是更多資訊(感謝 Thomas Levesque)。要更改生成的名稱,請使用該[XmlType]屬性。

像這樣定義自己的:

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

 public V Value 
 { get; set; }
}

引用自:https://stackoverflow.com/questions/2658916