Подтвердить что ты не робот

Легкий способ преобразования словаря <string, string> в xml и наоборот

Интересно, есть ли быстрый способ, возможно, с linq?, конвертировать словарь в XML-документ. И способ конвертировать xml обратно в словарь.

XML может выглядеть так:

<root>
      <key>value</key>
      <key2>value</key2>
</root>
4b9b3361

Ответ 1

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

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);
}

Ответ 2

Вы можете использовать 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();
            }
        }
    }

Ответ 3

Просто используйте это для XML для словаря:

     public static Dictionary<string, string> XmlToDictionary
                                        (string key, string value, XElement baseElm)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();

            foreach (XElement elm in baseElm.Elements())
            { 
                string dictKey = elm.Attribute(key).Value;
                string dictVal = elm.Attribute(value).Value;

                dict.Add(dictKey, dictVal);

            }

            return dict;
        }

Словарь XML:

 public static XElement DictToXml
                  (Dictionary<string, string> inputDict, string elmName, string valuesName)
        {

            XElement outElm = new XElement(elmName);

            Dictionary<string, string>.KeyCollection keys = inputDict.Keys;

            XElement inner = new XElement(valuesName);

            foreach (string key in keys)
            {
                inner.Add(new XAttribute("key", key));
                inner.Add(new XAttribute("value", inputDict[key]));
            }

            outElm.Add(inner);

            return outElm;
        }

XML:

<root>
  <UserTypes>
    <Type key="Administrator" value="A"/>
    <Type key="Affiliate" value="R" />
    <Type key="Sales" value="S" />
  </UserTypes>
</root>

Вы просто передаете элемент UserTypes этому методу, а вуаля вы получаете словарь с соответствующими ключами и значениями и наоборот. После преобразования словаря добавьте элемент в объект XDocument и сохраните его на диске.

Ответ 4

Что-то вроде этого для IDictionary

XElement root = new XElement("root");

foreach (var pair in _dict)
{
    XElement cElement = new XElement("parent", pair.Value);
    cElement.SetAttributeValue("id", pair.Key);
    el.Add(cElement);
}

Это создало следующий XML:

<root>
  <parent id="2">0</parent>
  <parent id="24">1</parent>
  <parent id="25">2</parent>
  <parent id="3">3</parent>
</root>

Ответ 5

  Dictionary<string, string> myDictionary = new Dictionary<string, string>();
  myDictionary.Add("key", "value");
  myDictionary.Add("key2", "value");
  var myJson = JsonConvert.SerializeObject(myDictionary);
  var myXml = JsonConvert.DeserializeXNode(myJson.ToString(),"root");
  Console.WriteLine(myXml.ToString());
  Console.Read();