写Web程序的时候程序配置使用System.Configuration,感觉很方便。当然了没有使用ConfigurationElementCollection
经过一天的努力也没有完成我的功能:
读取下面的配置文件使用 ConfigurationElementCollection,整整一天也没有成功。
<CommunicateSettings>
<Communicate name="test">
<Appender name="AdoNetAppender1" type="AdoNetAppender.AdoNetAppender" dll="AdoNetAppender1.dll">
<connectionString value="aaaa" />
<commandText value="bbbb" />
</Appender>
<Analysis name="AutomaticRain" type="AutomaticRain.RainAnalysis" dll="AutomaticRain.dll">
</Analysis>
</Communicate>
<Communicate name="test2">
<Appender name="AdoNetAppender2" type="AdoNetAppender.AdoNetAppender" dll="AdoNetAppender2.dll">
<connectionString value="aaaa" />
<commandText value="bbbb" />
</Appender>
<Analysis name="AutomaticRain" type="AutomaticRain.RainAnalysis" dll="AutomaticRain.dll">
</Analysis>
</Communicate>
</CommunicateSettings>
他只能读取下面的格式
<CommunicateSettings>
<Communicate name="test1" type="HongDian.GprsDTU" dll="HongDian.dll" />
<Communicate name="test2" type="HongDian.GprsDTU" dll="HongDian.dll" />
</CommunicateSettings>
无法只能使用原先的类库实现功能。
使用泛型反射的方法来实现。类似的代码如下:
public class AppConfigurationManage<T> where T:new()
{
public static IList<T> GetObjectList(string node)
{
IList<T> objectList = new List<T>();
XmlDocument xmldoc = new XmlDocument();
if (File.Exists(XMLConfig.XmlFileName))
{
xmldoc.Load(XMLConfig.XmlFileName);
string tempString = string.Format("/configuration/{0}", node);
XmlNodeList nodeList = xmldoc.SelectNodes(tempString);
Type type;
PropertyInfo propertyInfo;
for(int i = 0; i < nodeList.Count; i++)
{
T model = new T();
type = model.GetType();
for (int j = 0; j < nodeList[i].Attributes.Count; j++)
{
propertyInfo = type.GetProperty(nodeList[i].Attributes[j].Name);
if (propertyInfo != null)
{
propertyInfo.SetValue(model, nodeList[i].Attributes[j].Value, null);
}
}
objectList.Add(model);
}
}
xmldoc = null;
return objectList;
}
}
调用方法:
IList<Config.Communicate> objectList = ChangHong.Configuration.AppConfigurationManage<Config.Communicate>.GetObjectList(@"CommunicateSettings/Communicate/Appender"); //此处的参数使用XPATH 语法选择非常灵活
另外,哪位大佬有时间或者有类似的项目能读取System.Configuration!
不知道System.Configuration与直接使用XmlDocument性能如何!
希望不惜赐教!