首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

将Dictionary <string,string>转换为xml的简便方法,反之亦然

将Dictionary<string,string>转换为xml的简便方法可以使用.NET框架自带的System.Xml.Serialization命名空间中的XmlSerializer类。以下是一个简单的示例代码:

代码语言:csharp
复制
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,并且可以在序列化和反序列化过程中保留键值对的顺序。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券