configSections为自定义节点,增加应用程序可移植性,用于配置文件上传路径,再深入应用可定义工厂方法需要加载创建的类。
1.配置configSections节点
[html]
view plain
copy
print
?
- <configSections>
- <section name ="MyName" type="LearningConfiguration.NameSectionHandler"/>
- </configSections>
- <MyName>
- <Add key="lu" name="lulu"></Add>
- <Add key="lu2" name="66"></Add>
- </MyName>
<configSections>
<section name ="MyName" type="LearningConfiguration.NameSectionHandler"/>
</configSections>
<MyName>
<Add key="lu" name="lulu"></Add>
<Add key="lu2" name="66"></Add>
</MyName>
2.定义NameSectionHandler类实现IConfigurationSectionHandler接口
[csharp]
view plain
copy
print
?
- namespace LearningConfiguration
- {
- public class NameSectionHandler : IConfigurationSectionHandler
- {
- #region 隐式实现接口
- public object Create(object parent, object configContext, System.Xml.XmlNode section)
- {
- Dictionary<string, string> names = new Dictionary<string, string>();
- string key = string.Empty;
- string name = string.Empty;
-
- //获取配置文件中自定义节点值
- foreach (XmlNode childNode in section.ChildNodes)
- {
- if (childNode.Attributes["key"] != null)
- {
- key = childNode.Attributes["key"].Value;
-
- if (childNode.Attributes["name"] != null)
- {
- name = childNode.Attributes["name"].Value;
- }
- else
- {
- name = string.Empty;
- }
-
- names.Add(key, name);
- }
- }
-
- return names;
- }
- #endregion
- }
- }
namespace LearningConfiguration
{
public class NameSectionHandler : IConfigurationSectionHandler
{
#region 隐式实现接口
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
Dictionary<string, string> names = new Dictionary<string, string>();
string key = string.Empty;
string name = string.Empty;
//获取配置文件中自定义节点值
foreach (XmlNode childNode in section.ChildNodes)
{
if (childNode.Attributes["key"] != null)
{
key = childNode.Attributes["key"].Value;
if (childNode.Attributes["name"] != null)
{
name = childNode.Attributes["name"].Value;
}
else
{
name = string.Empty;
}
names.Add(key, name);
}
}
return names;
}
#endregion
}
}
3.调用
[csharp]
view plain
copy
print
?
- protected void Page_Load(object sender, EventArgs e)
- {
- Dictionary<string, string> names = ConfigurationManager.GetSection("MyName") as Dictionary<string, string>;
- if (names != null)
- {
- //输出:lulu66
- foreach (string key in names.Keys)
- {
- Response.Write(names[key]);
- }
- }
- }
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, string> names = ConfigurationManager.GetSection("MyName") as Dictionary<string, string>;
if (names != null)
{
//输出:lulu66
foreach (string key in names.Keys)
{
Response.Write(names[key]);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)