开发者

How to convert a xml string into a list of dictionaries?

开发者 https://www.devze.com 2023-01-14 19:41 出处:网络
string xml=\"< theme> <colors> <color&开发者_StackOverflowgt; <code>1</code>
string xml="< theme>

<colors>

<color&开发者_StackOverflowgt;
<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.


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.


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消