// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections; using System.Xml; namespace E { public class MainClass { public static string Hashtable2String(Hashtable ht) { XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("all")); foreach(DictionaryEntry de in ht) { XmlElement e = doc.CreateElement("entry"); XmlElement k = doc.CreateElement("key"); XmlElement v = doc.CreateElement("value"); k.AppendChild(doc.CreateTextNode((string)de.Key)); v.AppendChild(doc.CreateTextNode((string)de.Value)); e.AppendChild(k); e.AppendChild(v); doc.DocumentElement.AppendChild(e); } return doc.OuterXml; } public static Hashtable String2Hashtable(string s) { Hashtable res = new Hashtable(); XmlDocument doc = new XmlDocument(); doc.LoadXml(s); XmlNodeList all = doc.GetElementsByTagName("entry"); foreach(XmlElement e in all) { string k = e.ChildNodes[0].FirstChild.Value; string v = e.ChildNodes[1].FirstChild.Value; res.Add(k, v); } return res; } public static void Main(string[] args) { Hashtable ht = new Hashtable(); ht.Add("key1", "val1"); ht.Add("key2", "val2"); ht.Add("key3", "val3"); string s = Hashtable2String(ht); Console.WriteLine(s); Hashtable ht2 = String2Hashtable(s); Console.WriteLine(ht2["key1"]); Console.WriteLine(ht2["key2"]); Console.WriteLine(ht2["key3"]); } } }