Bill
Bill

Reputation: 2352

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

Upvotes: 3

Views: 698

Answers (2)

juharr
juharr

Reputation: 32286

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.

Upvotes: 2

Vadim Sentiaev
Vadim Sentiaev

Reputation: 761

Why you dont't use this?

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

Upvotes: 4

Related Questions