Nested XML to Dictionary

KooCracked

New Member
I am trying to convert an XML data into dictionary. I am having problems with identical node names. C# .Net 3.5Sample XML = the problem is I have no control over this. I just need to process it.\[code\]<?xml version="1.0" encoding="utf-8"?><Root> <a1>val1</a1> <a2>val2</a2> <Parameter> <ParameterName>param1</ParameterName> <ParameterValue>paramval1</ParameterValue> </Parameter> <Parameter> <ParameterName>param2</ParameterName> <ParameterValue>paramval2</ParameterValue> </Parameter></Root>\[/code\]My attempt: \[code\]XMLStream.Position = 0; XElement xmlDetails2 = XElement.Load(new System.IO.StreamReader(XMLStream)); var x = xmlDetails2.Elements().ToDictionary( e => e.Name.LocalName, e => e.Elements() .ToDictionary( f => f.Name.LocalName, f => f.Value));\[/code\]Error I am getting (which makes sense of course):\[code\]An item with the same key has already been added.\[/code\]Expected result ( from example xml ) :\[code\]a1 => val1a2 => val2param1 => paramval1param2 => paramval2...\[/code\]I created my own based on @L.B suggestion. It's not the best solution but it works for now.\[code\]public void XMLTODictionary(XElement xmlDetails, ref Dictionary<string, string> dic){ foreach (var node in xmlDetails.Elements()) { if (node.Name.LocalName.Equals("parameter", StringComparison.CurrentCultureIgnoreCase)) { dic.Add(node.Element("ParameterName").Value, node.Element("ParameterValue").Value); } else { dic.Add(node.Name.LocalName, node.Value); } }}\[/code\]
 
Back
Top