Converting an XML-document to a dictionary Converting an XML-document to a dictionary xml xml

Converting an XML-document to a dictionary


You could use linq to xml to do what you want (if I understand what you want)

string data = "<data><test>foo</test><test>foobbbbb</test><bar>123</bar><username>foobar</username></data>";XDocument doc = XDocument.Parse(data);Dictionary<string, string> dataDictionary = new Dictionary<string, string>();foreach (XElement element in doc.Descendants().Where(p => p.HasElements == false)) {    int keyInt = 0;    string keyName = element.Name.LocalName;    while (dataDictionary.ContainsKey(keyName)) {        keyName = element.Name.LocalName + "_" + keyInt++;    }    dataDictionary.Add(keyName, element.Value);}


XML Data

<?xml version="1.0" encoding="UTF-8"?><data>    <resource key="123">foo</resource>    <resource key="456">bar</resource>    <resource key="789">bar</resource>  </data>

Conversion Code

string s = "<data><resource key=\"123\">foo</resource><resource key=\"456\">bar</resource><resource key=\"789\">bar</resource></data>";XmlDocument xml = new XmlDocument();xml.LoadXml(s);XmlNodeList resources = xml.SelectNodes("data/resource");SortedDictionary<string,string> dictionary = new SortedDictionary<string,string>();foreach (XmlNode node in resources){   dictionary.Add(node.Attributes["key"].Value, node.InnerText);}

This question was asked before here and so you can find the all answers in this link :

convert xml to sorted dictionary

Hope it helps.


Your question's really not very clear, but I think this does what you want:

XmlDocument doc = new XmlDocument();doc.LoadXml(@"<xml><mengde>100</mengde><type>2</type><foo>bar</foo></xml>");Dictionary<string, string> d = new Dictionary<string, string>();foreach (XmlNode n in doc.SelectNodes("/xml/*"){   d[n.Name] = n.Value;}