Простой способ преобразовать Словарь <строка, строка> к xml и наоборот

Первый выпуск должен удостовериться, что тип Отладчика установлен на смешанный. Тогда Вы получаете полезные исключения.

39
задан Cœur 9 June 2018 в 16:03
поделиться

2 ответа

Словарь к элементу:

Dictionary<string, string> dict = new Dictionary<string,string>();
XElement el = new XElement("root",
    dict.Select(kv => new XElement(kv.Key, kv.Value)));

От элемента к словарю:

XElement rootElement = XElement.Parse("<root><key>value</key></root>");
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach(var el in rootElement.Elements())
{
   dict.Add(el.Name.LocalName, el.Value);
}
85
ответ дан 27 November 2019 в 02:11
поделиться

Вы можете использовать DataContractSerializer. Код ниже.

    public static string SerializeDict()
    {
        IDictionary<string, string> dict = new Dictionary<string, string>();
        dict["key"] = "value1";
        dict["key2"] = "value2";
        // serialize the dictionary
        DataContractSerializer serializer = new DataContractSerializer(dict.GetType());

        using (StringWriter sw = new StringWriter())
        {
            using (XmlTextWriter writer = new XmlTextWriter(sw))
            {
                // add formatting so the XML is easy to read in the log
                writer.Formatting = Formatting.Indented;

                serializer.WriteObject(writer, dict);

                writer.Flush();

                return sw.ToString();
            }
        }
    }
12
ответ дан 27 November 2019 в 02:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: