您可以使用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