tags:

views:

59

answers:

3
string xml="< theme>

<colors>

<color>
<code>1</code>
<name>blue</name>
<priority>5</priority>
</color>

<color>
<code>2</code>
<name>red</name>
<priority>2</priority>
</color>

<color>
<code>3</code>
<name>green</name>
<priority>7</priority>
</color>

</colors>
</theme>"

I would like to convert this xml string into a List of dictionaries called, say, 'colors'. For example:

List< Dictionary< string, string>> colors=new List< Dictionary< string, string>>();   
colors=//Magic happens here  

colors[0]["name"] would return 'blue'  
colors[2]["priority"] would return '7'  

etc.

Thanks.

+3  A: 

Assuming you're using LINQ to XML, that's relatively easy:

var query = doc.Descendants("colors")
               .Elements() // Get to each "color" element
               .Select(outer => outer.Elements()
                                     .ToDictionary(x => x.Name.LocalName,
                                                   x => x.Value))
               .ToList();

Let me know if any of that doesn't make sense to you.

EDIT: Oops, that would have been a List<Dictionary<XName, string>> before. Fixed :)

EDIT: I note in your comments that you were using fully qualified names. Try it with these using directives:

using System.Linq;
using System.Xml.Linq;

They're required to find the extension methods.

Jon Skeet
Thanks Jon. I take it that doc is this: System.Xml.Linq.XElement.Parse(xml) (the xml being stored in a string called 'xml') Correct?
Anthony
I get this error message:"An item with the same key has already been added". Is the following correct? System.Xml.Linq.XElement doc = System.Xml.Linq.XElement.Parse(xml);
Anthony
@Anthony: Doh, sorry - slight typo. Fixing...
Jon Skeet
What I meant is that 'Elements' does not exist. For example this simply doesn't compile: doc.Descendants("colors").Elements() because Elements is not a valid method here. Try in visual studio.
Anthony
@Anthony: Do you have using directives for System.Linq and System.Xml.Linq? It works fine for me...
Jon Skeet
I had forgotten System.Xml.Linq.... Oops. Thanks a lot Jon!!!
Anthony
+1  A: 

using LINQ:

        var d = XDocument.Parse(x);
        var l = new List<Dictionary<string, string>>(
            from color in d.Root.Element("colors").Elements("color")
            select color.Elements().ToDictionary(k => k.Name.LocalName, k=>k.Value)

            );

(where X is the string)

Yossarian
Any reason why you're constructing the list explicitly instead of just using ToList?
Jon Skeet
@Jon Skeet: in fact, I'm not sure now. Maybe I used it to demonstrate, that you will get exactly new `List< Dictionary<string, string>>`.
Yossarian
A: 

I find Jon's answer more convenient if you're using LINQ to XML, otherwise you might want to check xsd.exe tool

http://msdn.microsoft.com/en-us/library/x6c1kb0s%28VS.71%29.aspx

http://shadym.blogspot.com/2009/12/how-to-create-c-class-from-xml-file-via.html

Shady M. Najib