Reputation: 2352
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
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
Reputation: 761
Why you dont't use this?
System.Configuration.ConfigurationManager.AppSettings["Prop1"];
Upvotes: 4