I am trying to convert an XML data into dictionary. I am having problems with identical node names. C# .Net 3.5
Sample XML = the problem is I have no control over this.
Here is a method which will distill the data into tuples and then output a dictionary. Note it doesn't check for duplicate keys, but that could be added:
string data = @"
val1
val2
param1
paramval1
param2
paramval2
";
var elements = XDocument.Parse( data )
.Element("Root")
.Descendants();
var asTupleChildren = elements.Where (e => e.HasElements)
.Select (e => new Tuple(e.Element("ParameterName").Value, e.Element("ParameterValue").Value ));
var asTupleElements = elements.Where (e => e.HasElements == false)
.Where (e => e.Name != "ParameterName" && e.Name != "ParameterValue" )
.Select (e => new Tuple(e.Name.ToString(), e.Value ));
var asDictionary = asTupleElements.Concat(asTupleChildren)
.ToDictionary (te => te.Item1, te => te.Item2);
/* asDictionary is a Dictionary (4 items)
a1 val1
a2 val2
param1 paramval1
param2 paramval2
*/