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,481
  • 8
  • 53
  • 104
Yanshof
  • 9,297
  • 18
  • 86
  • 178

4 Answers4

9

You're looking for the ToDictionary() method:

root.Elements().ToDictionary(x => x.Name.LocalName, x => x.Value)
Anoop Vaidya
  • 45,913
  • 15
  • 108
  • 138
SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
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
  • 52,773
  • 10
  • 120
  • 121
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,713
  • 6
  • 59
  • 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
  • 170,430
  • 35
  • 234
  • 261