简体   繁体   中英

Linq to XML - Multiple Elements into Single Class

I have the following XML:

<appSettings>
   <add key="Prop1" value="1" />
   <add key="Prop2" value="2" />
</appSettings>

Is there a LINQ to XML query to load this section to a single instance of a ConfigProp class?

public class ConfigProp
{
   public string Prop1 {get; set;}
   public string Prop2 {get; set;}
}

Why you dont't use this?

System.Configuration.ConfigurationManager.AppSettings["Prop1"];

You'll want something like this

var xml = XElement.Parse(
    @"<appSettings><add key=""Prop1"" value=""1"" /><add key=""Prop2"" value=""2"" /></appSettings>");
new ConfigProp
{
    Prop1=xml
        .Elements("add")
        .Single(element=>element.Attribute("key").Value == "Prop1")
        .Attribute("value")
        .Value,
    Prop2 = xml
        .Elements("add")
        .Single(element => element.Attribute("key").Value == "Prop2")
        .Attribute("value")
        .Value
};

Note that if your xml does not contain the Prop1 and Prop2 keys this with throw an exception.

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