您可以使用ExtendedXmlSerializer。 如果你有一個類:
public class TestClass
{
public Dictionary<int, string> Dictionary { get; set; }
}
,並創建該類的實例:
var obj = new TestClass
{
Dictionary = new Dictionary<int, string>
{
{1, "First"},
{2, "Second"},
{3, "Other"},
}
};
可以序列使用ExtendedXmlSerializer這個對象:
var serializer = new ConfigurationContainer()
.UseOptimizedNamespaces() //If you want to have all namespaces in root element
.Create();
var xml = serializer.Serialize(
new XmlWriterSettings { Indent = true }, //If you want to formated xml
obj);
輸出XML的樣子:
<?xml version="1.0" encoding="utf-8"?>
<TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples">
<Dictionary>
<sys:Item>
<Key>1</Key>
<Value>First</Value>
</sys:Item>
<sys:Item>
<Key>2</Key>
<Value>Second</Value>
</sys:Item>
<sys:Item>
<Key>3</Key>
<Value>Other</Value>
</sys:Item>
</Dictionary>
</TestClass>
可以從nuget安裝ExtendedXmlSerializer或運行以下命令:
Install-Package ExtendedXmlSerializer
或使用代碼:http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx – prostynick 2010-05-26 09:30:51
什麼方法/ Dictionary中的屬性暗示它必須作爲散列表來實現? Dictionary和IDictionary是Key/Value對的集合,與Hashtable實現不同。 從序列化的角度來看,我們的目標似乎是將數據從易失性存儲器中取出,以便能夠在稍後時間加載它。將任何*數據重新加載到接口的不同具體實現中將導致不同的行爲。 – Jeremy 2011-06-16 12:48:32
序列化KeyValuePair不起作用。你最終會得到一個空標籤。請參閱:https://stackoverflow.com/questions/2658916/serializing-a-list-of-key-value-pairs-to-xml – NullAndVoid 2017-07-05 08:56:08