我有以下app.config自定义部分:
<myCustomSection>
<person1 name = "John" age = "30">
<person2 name = "Mike" age = "46">
</muCustomSection>
以下代码在System.Configuration.ConfigurationManager:
的帮助下解析它public class MyCustomCongifuration : ConfigurationSection {
[ConfigurationProperty("person1", IsRequired = true)]
public PersonConfiguration Person1
{
get => (PersonConfiguration)this["person1"];
set => this["person1"] = value;
}
[ConfigurationProperty("person2", IsRequired = true)]
public PersonConfiguration Person2
{
get => (PersonConfiguration)this["person2"];
set => this["person2"] = value;
}
}
我想重构代码以使用以下app.config:
<myCustomSection>
<person name = "John" age = "30">
<person name = "Mike" age = "46">
</muCustomSection>
我希望在MyCustomConfiguration对象中获得PersonConfiguration列表:
var configuration = ConfigurationManager.GetSection("myCustomSection") as MyCustomConfiguration;
var persons = configuration.Persons; // returns List<PersonConfiguration>
是否有可能,我该怎么做?
答案 0 :(得分:1)
.NET Framework确实支持在其配置中包含项目列表,但不完全按照您的列出。如果查看文件的appSettings
部分,可以看到集合的示例:
<appSettings>
<add key="foo" value="Fizz" />
<add key="bar" value="Buzz" />
</appSettings>
这是基于专门的集合ConfigurationElementCollection
构建的,它允许您将add
remove
和clear
函数建模为XML,以便构建项目列表。< / p>
首先,将name
的{{1}}属性标记为关键字。我假设这个人的名字适合作为密钥标识符;如果你想出一个不同的标识符,请使用它。
PersonConfiguration
创建源自[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
的自定义集合,以便返回某个人的键值。
ConfigurationElementCollection
然后将此集合添加到自定义配置部分的类:
[ConfigurationCollection(typeof(PersonConfiguration))]
public class PersonConfigurationElementCollection : ConfigurationElementCollection
{
protected override PersonConfiguration CreateNewElement()
{
return new PersonConfiguration();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((PersonConfiguration)element).Name;
}
}
您现在可以创建一组人员:
public class MyCustomCongifuration : ConfigurationSection
{
[ConfigurationProperty("people", IsDefaultCollection = true)]
public PersonConfigurationElementCollection People
{
get { return (PersonConfigurationElementCollection)this["people"]; }
set { this["people"] = value; }
}
}
如果要将该配置集合转换为列表,可以使用一点Linq:
<myCustomSection>
<people>
<add name="John" age="30" />
<add name="Mike" age="46" />
</people>
</muCustomSection>
答案 1 :(得分:0)
我不知道你怎么能用ConfigurationManager做到这一点,但是另一种方法可能是使用XML Linq:
using System.Xml.Linq;
XDocument doc = XDocument.Load("C:\path\to\file.config");
var persons = doc.Element("configuration").Element("myCustomSection").Descendants("person");
foreach (var person in persons)
{
var Name = Attribute("name").Value;
var Age = Attribute("age").Value;
}
您可以使用以下内容删除项目:
doc.Element("configuration").Elements("myCustomSection").First(s =>(string)s.Attribute("name") == "Name you want to find").Remove();