我们有一个基本上是Xml的设置文件,我们正在为我们正在编写的可插入模块进行扩展。基本上我们想要使用我们现有的Xml设置,但允许在它们上面写入扩展方法。如果我们有一个像这样的Xml文件,那就很简短:
<Settings>
<SettingsOne Key1_1="Value1"
Key1_2="Value2" />
<SettingsTwo Key2_1="Value1"
Key2_2="Value2" />
</Settings>
我们如何将其作为SettingsEntry的集合加载,其中SettingsEntry如下所示:
public class SettingsEntry
{
public string Section { get; set; }
public string Key { get; set; }
public string Value { get; set; }
}
其中Section将是&#34; SettingsOne&#34;,Key将是&#34; Key1_1&#34;和价值将是&#34;价值1&#34;。
这甚至是可能还是我走上了黑暗的道路?
编辑:
好的,Linq对Xml的建议是生命保存,我试图用XmlSerializer做到这一点!下面是我到目前为止,有没有办法把它变成一个选择,而不是像我下面的两个选择:
var root = XElement.Load(pathToXml);
var sections = from el in root.Elements()
select el.Name;
List<SettingsEntry> settings = new List<SettingsEntry>();
foreach (var item in sections)
{
var attributes = from el in root.Elements(item).Attributes()
select new SettingsEntry()
{
Section = item.LocalName,
Key = el.Name.LocalName,
Value = el.Value
};
settings.AddRange(attributes);
}
return settings;
编辑2:
这似乎有效。
var sections = from el in root.Elements()
from a in root.Elements(el.Name).Attributes()
select new SettingsEntry()
{
Section = el.Name.LocalName,
Key = a.Name.LocalName,
Value = a.Value
};
答案 0 :(得分:0)
您可以在一个LINQ查询中执行此操作:
var attributes = from attribute in root.Elements().Attributes()
select new SettingsEntry()
{
Section = attribute.Parent.Name.LocalName,
Key = attribute.Name.LocalName,
Value = attribute.Value
};
return attributes.ToList();
答案 1 :(得分:0)
var xml = @"
<Settings>
<SettingsOne Key1_1= ""Value1"" Key1_2= ""Value1""></SettingsOne>
<SettingsTwo Key2_1= ""Value1"" Key2_2= ""Value1""></SettingsTwo>
</Settings>"
var root = XDocument.Parse(xml);
var q = root.Elements("Settings").Descendants();
List<SettingsEntry> settings = (from el in root.Elements("Settings").Descendants()
select new SettingsEntry()
{
Section = el.Name.ToString(),
Key = el.FirstAttribute.Value,
Value = el.LastAttribute.Value
}).ToList();
您可能需要稍微玩一下才能获得您想要的确切对象,但这是朝着正确方向发展的重要推动力。