Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to convert a Dictionary<string, string> to xml and vice versa

Wondering if there is a fast way, maybe with linq?, to convert a Dictionary<string,string> into a XML document. And a way to convert the xml back to a dictionary.

XML can look like:

<root>       <key>value</key>       <key2>value</key2> </root> 
like image 358
mrblah Avatar asked Nov 25 '09 20:11

mrblah


People also ask

What is dictionary in XML?

A multiple-line comment is used to show the copyright information. "dictionary" is the root element. Attributes are used in elements: "word", "definition" and "update". "update" is an empty element with no content. "word" is a nested element, and repeated twice.

What is dictionary string string in C#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs.

Can a dictionary key be a string in C#?

Add elements to a C# Dictionary Both types are generic so it can be any . NET data type. The following Dictionary class is a generic class and can store any data type. This class is defined in the code snippet creates a dictionary where both keys and values are string types.


2 Answers

Dictionary to Element:

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

Element to Dictionary:

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); } 
like image 86
LorenVS Avatar answered Sep 22 '22 17:09

LorenVS


You can use DataContractSerializer. Code below.

    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();             }         }     } 
like image 37
dcp Avatar answered Sep 23 '22 17:09

dcp