My input is XElement object - and i need to convert this object to Dictionary
The XElement is look like this
<Root>
<child1>1</child1>
<child2>2</child2>
<child3>3</child3>
<child4>4</child4>
</Root>
And the output that i actually need to return is
开发者_如何学GoDictionary that look like this
[ Child1, 1 ]
[ Child2, 2 ]
[ Child3, 3 ]
[ Child4, 4 ]
How can i do it ?
thanks for any help.
You're looking for the ToDictionary()
method:
root.Elements().ToDictionary(x => x.Name.LocalName, x => x.Value)
var doc = XDocument.Parse(xml);
Dictionary<string, int> result = doc.Root.Elements()
.ToDictionary(k => k.Name.LocalName, v => int.Parse(v.Value));
You're all missing the point.
The keys are meant to be "ChileX", as in the country. :)
var xml = XElement.Parse("<Root><child1>1</child1><child2>2</child2><child3>3</child3><child4>4</child4></Root>");
var d = xml.Descendants()
.ToDictionary(e => "Chile" + e.Value, e => v.Value);
You can try
XElement root = XElement.Load("your.xml");
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (XElement el in root.Elements())
dict.Add(el.Name.LocalName, el.Value);
or
For linq solution check @jon skeet answer : Linq to XML -Dictionary conversion
精彩评论