我正在创建一个类来从配置文件中读取/写入自定义配置。这是配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Country" type="CustomeConfig.CountryConfig, CustomeConfig"/>
</configSections>
<Country>
<State>
<City>
<add name="a" age="20"></add>
<add name="b" age="20"></add>
<add name="c" age="20"></add>
</City>
<City>
<add name="d" age="20"></add>
<add name="e" age="20"></add>
<add name="f" age="20"></add>
</City>
</State>
</Country>
</configuration>
并且读取配置文件的代码在
之下 namespace CustomeConfig
{
public class CountryConfig : ConfigurationSection
{
[ConfigurationProperty("State")]
public StateCollection States
{
get { return ((StateCollection)(base["State"])); }
}
}
[ConfigurationCollection(typeof(CityCollection))]
public class StateCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new CityCollection();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((CityCollection)(element));
}
[ConfigurationProperty("City", IsDefaultCollection = false)]
public CityCollection this[int idx]
{
get
{
return (CityCollection)BaseGet(idx);
}
}
}
[ConfigurationCollection(typeof(User))]
public class CityCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new User();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((User)(element)).name;
}
public User this[int idx]
{
get
{
return (User)BaseGet(idx);
}
}
//public override ConfigurationElementCollectionType CollectionType
//{
// get { return ConfigurationElementCollectionType.BasicMap; }
//}
}
public class User : ConfigurationElement
{
[ConfigurationProperty("name", DefaultValue = "", IsKey = true, IsRequired = true)]
public string name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("age", DefaultValue = "", IsKey = false, IsRequired = true)]
public string servername
{
get { return (string)base["age"]; }
set { base["age"] = value; }
}
}
}
static void Main(string[] args)
{
CountryConfig config = (CountryConfig)System.Configuration.ConfigurationSettings.GetConfig("Country");
Console.ReadLine();
}
一旦我运行代码,它就会显示错误“元素<city>
可能只在本节中出现一次”。由于有两个<city>
部分。
答案 0 :(得分:0)
如果我遇到配置部分的问题,我通常在xml文件中的部分中没有数据。然后我通过代码填充数据并保存。然后你可以很容易地弄清楚你在xml中做错了什么。
将其放入“自定义”部分,以便能够保存代码填充部分:
public void Save()
{
Configuration config =
ConfigurationManager.OpenExeConfiguration(spath);
CountryConfig section = (CountryConfig)config.Sections["Country"];
section.States = this.States; //Copy the changed data
config.Save(ConfigurationSaveMode.Full);
}
那么你可以使用你的C#代码来计算配置的结构(有助于发现两者之间的不一致)