如何扫描XElement并将所有元素(带有值)放在Dictionary中?

我的输入是XElement对象 – 我需要将此对象转换为Dictionary

XElement看起来像这样

 1 2 3 4  

而我实际需要返回的输出是

看起来像这样的字典

 [ Chile1, 1 ] [ Chile2, 2 ] [ Chile3, 3 ] [ Chile4, 4 ] 

我该怎么做 ?

谢谢你的帮助。

您正在寻找ToDictionary()方法:

 root.Elements().ToDictionary(x => x.Name.LocalName, x => x.Value) 
 var doc = XDocument.Parse(xml); Dictionary result = doc.Root.Elements() .ToDictionary(k => k.Name.LocalName, v => int.Parse(v.Value)); 

你们都错过了这一点。

钥匙的意思是“ChileX”,就像在国内一样。 🙂

 var xml = XElement.Parse("1234"); var d = xml.Descendants() .ToDictionary(e => "Chile" + e.Value, e => v.Value); 

你可以试试

 XElement root = XElement.Load("your.xml"); Dictionary dict = new Dictionary(); foreach (XElement el in root.Elements()) dict.Add(el.Name.LocalName, el.Value); 

要么

对于linq解决方案,请检查@jon双向答案: Linq to XML -Dictionary转换