Easy way to convert a Dictionary<string, string> to xml and vice versa
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);
}
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();
}
}
}
Just use this for XML to Dictionary:
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;
}
Dictionary to 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;
}
The XML:
<root>
<UserTypes>
<Type key="Administrator" value="A"/>
<Type key="Affiliate" value="R" />
<Type key="Sales" value="S" />
</UserTypes>
</root>
You just pass the element UserTypes to that method and voila you get a dictionary with the coresponding keys and values and vice versa. After converting a dictionary append the element to XDocument object and save it on the disk.