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. I just need to process it.
<?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>
My attempt:
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));
Error I am getting (which makes sense of course):
An item with the same key has already been added.
Expected result ( from example xml ) :
a1 => val1
a2 => val2
param1 => paramval1
param2 => paramval2
...
I created my own based on @L.B suggestion. It's not the best solution but it works for now.
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);
}
}
}