将Dictionary<string,string>转换为xml的简便方法可以使用.NET框架自带的System.Xml.Serialization命名空间中的XmlSerializer类。以下是一个简单的示例代码:
using System;
using System.IO;
using System.Xml.Serialization;
public class Program
{
public static void Main()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("key1", "value1");
dict.Add("key2", "value2");
dict.Add("key3", "value3");
XmlSerializer serializer = new XmlSerializer(typeof(Dictionary<string, string>));
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, dict);
string xml = writer.ToString();
Console.WriteLine(xml);
}
string xmlStr =<ArrayOfKeyValueOfstringstring xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\"><KeyValueOfstringstring><Key>key1</Key<Value>value1</Value></KeyValueOfstringstring><KeyValueOfstringstring><Key>key2</Key<Value>value2</Value></KeyValueOfstringstring><KeyValueOfstringstring><Key>key3</Key<Value>value3</Value></KeyValueOfstringstring></ArrayOfKeyValueOfstringstring>";
using (StringReader reader = new StringReader(xmlStr))
{
Dictionary<string, string> deserializedDict = (Dictionary<string, string>)serializer.Deserialize(reader);
foreach (var item in deserializedDict)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
}
}
反之亦然,即将XML转换为Dictionary<string,string>,可以使用上述代码中的反序列化过程。
此方法适用于将Dictionary<string,string>转换为XML,并且可以在序列化和反序列化过程中保留键值对的顺序。
领取专属 10元无门槛券
手把手带您无忧上云