kevin0304
kevin0304

Reputation: 19

Convert XML to Dictionary<String,String>

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

Answers (1)

jdweng
jdweng

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

Related Questions