【发布时间】:2012-03-16 00:24:29
【问题描述】:
我正在创建一个类来从配置文件中读取/写入自定义配置。这是配置文件
<?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> 部分。
【问题讨论】: