简体   繁体   中英

Using LINQ to parse XML into Dictionary

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>

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

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);

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 );

Your call to ToDictionary needs a key and value selector. Starting with that you have, it can be

var dictionary = yourQuery.ToDictionary(item => item.Name, item => item.Value);

It isn't necessary to have the query as you're just doing a projection. Move the projection into the call to ToDictionary() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM