.net 自定义WebConfig中的节点,方法如下:
1、创建自定义节点类CompanySection。该类中的属性(Path、CompanyName、IsPrivate)与WebConfig中的自定义节点名称对应。
namespace Test
{
public class CompanySection
{
private string _path = "";
private string _companyName = "";
private bool _isPrivate = false;
public string Path
{
get { return _path; }
set { _path = value; }
}
public string CompanyName
{
get { return _companyName; }
set { _companyName = value; }
}
public bool IsPrivate
{
get { return _isPrivate; }
set { _isPrivate = value; }
}
}
}
2、创建类CompanySectionHandler。该类继承IConfigurationSectionHandler接口并实现Create()方法
namespace Test
{
public class CompanySectionHandler : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
CompanySection para = new CompanySection();//自定义节点类
foreach (XmlNode xn in section.ChildNodes)
{
switch (xn.Name)
{
case "path":
para.Path = xn.SelectSingleNode("@value").InnerText;
break;
case "companyName":
para.CompanyName = xn.SelectSingleNode("@value").InnerText;
break;
case "isPrivate":
para.IsPrivate = bool.Parse(xn.SelectSingleNode("@attribute").InnerText);
break;
}
}
return para;
}
}
}
3、配置WebConfig。在<configuration>节点下增加如下节点
<configuration>
<configSections>
<sectionGroup name ="CompanyGroups">
<section name ="CompanySection" type ="Test.CompanySectionHandler,Test"/>
</sectionGroup>
</configSections>
<CompanyGroups>
<CompanySection>
<path value="NONE"/>
<companyName value="Robsun"/>
<isPrivate attribute="true"/>
</CompanySection>
</CompanyGroups>
<system.web>
</system.web>
</configuration>
4、调用
protected void Page_Load(object sender, EventArgs e)
{
Test.CompanySection para =
ConfigurationManager.GetSection("CompanyGroups/CompanySection") as Test.CompanySection;
Response.Write("CompanyName: " + para.CompanyName + "<br>");
Response.Write("Path: " + para.Path + Environment.NewLine + "<br>");
Response.Write("isPrivate: " + para.IsPrivate.ToString() + "<br>");
}