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);
}
}
}
How about using DynamicXml here
EDIT
A generic approach would be to get a dictionary
Dictionary<string,object>But there are some problems while converting an xml to dictionary. For example
dict["a1"]would return val1, but what would this xml returndict["a1"]["name"]? valAttr or valName?And considering your example, the only difference between
dict["a1"]anddict["Parameter"]is thatParameter exists more than once under the same parent and it should be thought as an array rather than a
single element.
DynamicXml tries to solve these issues. Of course there
is a lot of room for improvement but It should work for basic needs.