Reputation: 19
i have been trying to convert this XML to a dictionnary but have all kinds of errors. Here's my XML
<product>
<name>AH</name>
<prod>AH</prod>
<time>Noon</time>
<txt>00A</txt>
</product>
I'm trying to get a dictionary with the Key equal to the txt and the value to prod. I have been trying this one but couldn't make it work:
Dictionary<string, string> result =
(from e in productsNames.Descendants() select new KeyValuePair<string, string>
(e.Element("txt").Value, e.Element("prod").Value)).ToDictionary(x => x.Key, x =>x.Value);
Can you help me? thanks in advance!
Upvotes: 0
Views: 84
Reputation: 34421
Easy :
string xml = @"<product>
<name>AH</name>
<prod>AH</prod>
<time>Noon</time>
<txt>00A</txt>
</product>";
XDocument doc = XDocument.Parse(xml);
Dictionary<string, string> dict = doc.Descendants("product")
.GroupBy(x => (string)x.Element("name"), y => (string)y.Element("prod"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
Upvotes: 1