0

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

Dictionary that look like this

[ Child1, 1 ]
[ Child2, 2 ]
[ Child3, 3 ]
[ Child4, 4 ]

How can i do it ?

thanks for any help.

Dean Kuga
  • 11,878
  • 8
  • 54
  • 108
Yanshof
  • 9,659
  • 21
  • 95
  • 195

4 Answers4

9

You're looking for the ToDictionary() method:

root.Elements().ToDictionary(x => x.Name.LocalName, x => x.Value)
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2
var doc = XDocument.Parse(xml);

Dictionary<string, int> result = doc.Root.Elements()
    .ToDictionary(k => k.Name.LocalName, v => int.Parse(v.Value));
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
2

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);
Mikael Östberg
  • 16,982
  • 6
  • 61
  • 79
1

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

Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263