[英]Linq to XML - Multiple Elements into Single Class
I have the following XML: 我有以下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? 是否有LINQ to XML查询将此部分加载到ConfigProp类的单个实例?
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. 请注意,如果您的xml不包含Prop1和Prop2键,则抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.