I have an xml like the following:
<NewDataSet>
<Person>
<FirstName>abc</FirstName>
<LastName>xyz</LastName>
<Address>12345abc</Address>
</Person>
<Person>
<FirstName>abcd</FirstName>
<LastName>pqr_xyz</LastName>
<Address>1111abc</Address>
</Person>
<Person>
<FirstName>abcde</FirstName>
<LastName>ghy_xyz</LastName>
<Address>98765abc</Address>
</Person>
</NewDataSet>
Now I want this xml into a dictionary. Following is the code I am using.
string data =
@"<NewDataSet><Person>...";
XDocument doc = XDocument.Parse(data);
Dictionary<string, string> dataDictionary = new Dictionary<string, string>();
foreach (XElement elem in doc.Descendants("Person"))
{
var row = elem.Descendants();
string str = elem.ToString();
foreach (XElement element in row)
{
string keyName = element.Name.LocalName;
dataDictionary.Add(keyName, element.Value);
}
yield return dataDictionary;
}
Now this code is not working. I know there is a silly mistake somewhere, can anyone please help me out? Here is a sample of somewhat similar requirement convert xdocument to IEnumerable<Dictionary<string, object>>, but I can not get it to work either.
thanks,
You were trying to use the same instance of the dataDictionary object which threw the argument exception. An item with the same key has already been added. To correct this you need to initialize the dataDictionary within the first for each loop.
Dictionary<string, string> dataDictionary = null;
foreach (XElement elem in doc.Descendants("Person"))
{
var row = elem.Descendants();
string str = elem.ToString();
dataDictionary = new Dictionary<string, string>();
foreach (XElement element in row)
{
string keyName = element.Name.LocalName;
dataDictionary.Add(keyName, element.Value);
}
yield return dataDictionary;
}