Linq to XML - multiple elements in one 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 into a single instance of the ConfigProp class?

public class ConfigProp
{
   public string Prop1 {get; set;}
   public string Prop2 {get; set;}
}
+3
source share
2 answers

You will need 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 keys Prop1 and Prop2, this throws an exception.

+2
source

Why aren't you using this?

System.Configuration.ConfigurationManager.AppSettings ["Prop1"];
+4
source

Source: https://habr.com/ru/post/1788489/


All Articles