[英]Linq to XML - Multiple Elements into Single Class
我有以下XML:
<appSettings>
<add key="Prop1" value="1" />
<add key="Prop2" value="2" />
</appSettings>
是否有LINQ to XML查詢將此部分加載到ConfigProp類的單個實例?
public class ConfigProp
{
public string Prop1 {get; set;}
public string Prop2 {get; set;}
}
你為什么不用這個?
System.Configuration.ConfigurationManager.AppSettings["Prop1"];
你會想要這樣的東西
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
};
請注意,如果您的xml不包含Prop1和Prop2鍵,則拋出異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.