使用LINQ to XML解析成字典 [英] Using LINQ to parse XML into Dictionary

查看:120
本文介绍了使用LINQ to XML解析成字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置文件,如:

I have a configuration file such as:

<ConfigurationFile>
    <Config name="some.configuration.setting" value="some.configuration.value"/>
    <Config name="some.configuration.setting2" value="some.configuration.value2"/>
    ...
</ConfigurationFile>



我想读这XML并将其转换为一个字典。我试着编码的东西liek这一点,但它显然是错误的,因为它不会编译

I am trying to read this to XML and convert it to a Dictionary. I tried coding something liek this but it is obviously wrong as it does not compile.

Dictionary<string, string> configDictionary = (from configDatum in xmlDocument.Descendants("Config")
                                               select new
                                               {
                                                   Name = configDatum.Attribute("name").Value,
                                                   Value = configDatum.Attribute("value").Value,
                                               }).ToDictionary<string, string>(Something shoudl go here...?);

如果有人能告诉我如何得到这个工作这将是非常有益的。我总是可以的,当然,阅读

If someone could tell me how to get this working it would be really helpful. I could always, of course, read it

推荐答案

要给出更详细的解答 - 您可以使用 ToDictionary 完全按照你在你的问题中写道。在缺少的一部分,你需要指定键选择和价值选择这是两个函数,告诉 ToDictionary 方法的对象的哪一部分,你转换是一个键,这是一个值。你已经提取这两种成一个匿名类型,所以你可以写:

To give a more detailed answer - you can use ToDictionary exactly as you wrote in your question. In the missing part, you need to specify "key selector" and "value selector" these are two functions that tell the ToDictionary method which part of the object that you're converting is a key and which is a value. You already extracted these two into an anonymous type, so you can write:

var configDictionary = 
 (from configDatum in xmlDocument.Descendants("Config")
  select new {
    Name = configDatum.Attribute("name").Value,
    Value = configDatum.Attribute("value").Value,
  }).ToDictionary(o => o.Name, o => o.Value);

请注意,我删除了泛型类型参数的规范。自动的C#编译器的数据(我们使用的是超载有三个通用参数的)。但是,你能避免使用匿名类型 - 在上面的版本,你只需将它打造为临时存储的值。最简单的版本将只是:

Note that I removed the generic type parameter specification. The C# compiler figures that automatically (and we're using an overload with three generic arguments). However, you can avoid using anonymous type - in the version above, you just create it to temporary store the value. The simplest version would be just:

var configDictionary = 
  xmlDocument.Descendants("Config").ToDictionary(
    datum => datum.Attribute("name").Value,
    datum => datum.Attribute("value").Value );

这篇关于使用LINQ to XML解析成字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆