.NET中自定义配置节点

**一.目的
** 一般应用都有自己的配置文件,如何将配置文件映射到.NET中的对象是有现实意义的事情,在Java中有一个digester开源项目实现了这个功能,下面我一步一步来说明.NET中如何更简单的实现他
二.实现
1.定义xsd架构文件,我们定义几个简单的架构
架构示图
源文件如下:

 1<xs:schema elementformdefault="qualified" id="MyConfig" targetnamespace="ConfigTest" xmlns="ConfigTest" xmlns:mstns="ConfigTest" xmlns:xs="  http://www.w3.org/2001/XMLSchema  ">
 2<xs:complextype mixed="true" name="select">
 3<xs:sequence></xs:sequence>
 4<xs:attribute name="id" type="xs:string"></xs:attribute>
 5<xs:attribute name="resultMap" type="xs:string"></xs:attribute>
 6<xs:attribute name="cacheModel" type="xs:string" use="optional"></xs:attribute>
 7<xs:attribute name="sql" type="xs:string"></xs:attribute>
 8</xs:complextype>
 9<xs:complextype mixed="true" name="update">
10<xs:sequence></xs:sequence>
11<xs:attribute name="id" type="xs:string"></xs:attribute>
12<xs:attribute name="parameterMap" type="xs:string"></xs:attribute>
13<xs:attribute name="sql" type="xs:string"></xs:attribute>
14</xs:complextype>
15<xs:element name="statements">
16<xs:complextype>
17<xs:sequence>
18<xs:element maxoccurs="unbounded" minoccurs="0" name="select" type="select"></xs:element>
19<xs:element maxoccurs="unbounded" minoccurs="0" name="update" type="update"></xs:element>
20</xs:sequence>
21</xs:complextype>
22</xs:element>
23</xs:schema>

2.使用xsd.exe生成对应于架构的配置类
xsd.exe MyConfig.xsd /c

//------------------------------------------------------------------------------
//

1<autogenerated>   
2// This code was generated by a tool.   
3// Runtime Version:2.0.40607.16   
4//   
5// Changes to this file may cause incorrect behavior and will be lost if   
6// the code is regenerated.   
7// </autogenerated>

//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=2.0.40607.16.
//
namespace ConfigDll
{

///

1<remarks></remarks>

[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "ConfigTest")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "ConfigTest", IsNullable = false)]
public class statements
{

private select[] selectField;

private update[] updateField;

///

1<remarks></remarks>

[System.Xml.Serialization.XmlElementAttribute("select")]
public select[] select
{
get
{
return this.selectField;
}
set
{
this.selectField = value;
}
}

///

1<remarks></remarks>

[System.Xml.Serialization.XmlElementAttribute("update")]
public update[] update
{
get
{
return this.updateField;
}
set
{
this.updateField = value;
}
}
}

///

1<remarks></remarks>

[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "ConfigTest")]
public class select
{

private string idField;

private string resultMapField;

private string cacheModelField;

private string sqlField;

///

1<remarks></remarks>

[System.Xml.Serialization.XmlAttributeAttribute()]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}

///

1<remarks></remarks>

[System.Xml.Serialization.XmlAttributeAttribute()]
public string resultMap
{
get
{
return this.resultMapField;
}
set
{
this.resultMapField = value;
}
}

///

1<remarks></remarks>

[System.Xml.Serialization.XmlAttributeAttribute()]
public string cacheModel
{
get
{
return this.cacheModelField;
}
set
{
this.cacheModelField = value;
}
}

///

1<remarks></remarks>

[System.Xml.Serialization.XmlTextAttribute()]

public string sql
{
get
{
return this.sqlField;
}
set
{
this.sqlField = value;
}
}
}

///

1<remarks></remarks>

[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "ConfigTest")]
public class update
{

private string idField;

private string parameterMapField;

private string sqlField;

///

1<remarks></remarks>

[System.Xml.Serialization.XmlAttributeAttribute()]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}

///

1<remarks></remarks>

[System.Xml.Serialization.XmlAttributeAttribute()]
public string parameterMap
{
get
{
return this.parameterMapField;
}
set
{
this.parameterMapField = value;
}
}

///

1<remarks></remarks>

[System.Xml.Serialization.XmlTextAttribute()]
public string sql
{
get
{
return this.sqlField;
}
set
{
this.sqlField = value;
}
}
}
}

3.实现IConfigurationSectionHandler接口

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;

#endregion

namespace ConfigDll
{
public class MyConfigHandler : IConfigurationSectionHandler
{
private Type _configType = typeof(statements);
private string _schemaResourceName = "ConfigDll.MyConfig.xsd";
private string _schemaNamespace = "ConfigTest";

public MyConfigHandler()
{
}

public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
XmlSerializer ser = new XmlSerializer(_configType);

// Create the XmlSchemaSet class.
XmlSchemaSet sc = new XmlSchemaSet();

// Add the schema to the collection.
Stream schemaStream = Assembly.GetAssembly(_configType).GetManifestResourceStream(_schemaResourceName);
sc.Add(_schemaNamespace, new XmlTextReader(schemaStream));

// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.XsdValidate = true;
settings.Schemas = sc;
settings.ValidationEventHandler += this.ValidationEventHandle;

XmlReader reader = XmlReader.Create(XmlReader.Create(new StringReader(section.OuterXml)), settings);
return ser.Deserialize(reader);
}

public void ValidationEventHandle(object sender, ValidationEventArgs args)
{
Console.WriteLine("\t验证错误:" + args.Message);
}

}
}
当然你可以建一个通用的校验类,这里只为演示
如果使用VS2003,校验需要使用XmlValidatingReader类,考虑到它在.NET2.0中已经过时所以使用新的方式

4.在App.Config中使用自定义配置节点

 1<configuration>
 2<configsections>
 3<section name="statements" type="ConfigDll.MyConfigHandler,ConfigDll"></section>
 4</configsections>
 5<statements xmlns="ConfigTest">
 6<select id="GetEmailAddressViaResultClass" resultclass="string">   
 7select Account_Email as value   
 8from Accounts   
 9where Account_ID = #value#   
10</select>
11<select id="GetAllEmailAddressesViaResultClass" resultclass="string">   
12select Account_Email   
13from Accounts   
14order by Account_ID   
15</select>
16<update id="UpdateAccountViaParameterMap" parametermap="update-params">   
17update Accounts set   
18Account_FirstName = ?,   
19Account_LastName = ?,   
20Account_Email = ?   
21where   
22Account_ID = ?   
23</update>
24<update id="UpdateAccountViaParameterMap2" parametermap="update-params2">   
25update Accounts set   
26Account_ID = ?,   
27Account_FirstName = ?,   
28Account_LastName = ?,   
29Account_Email = ?   
30where   
31Account_ID = ?   
32</update>
33</statements>
34</configuration>

注意:设置上Handler
在应用程序中得到配置
statements sts = (statements)ConfigurationSettings.GetConfig("statements");

5.在其他配置文件中使用
XmlDocument doc = new XmlDocument();
doc.Load("Extend_Test.xml");
statements sts = (statements)new MyConfigHandler().Create(null, null, doc.DocumentElement);

三.其他
环境:VS2005
难成好文章,只是凑凑热闹

Published At
Categories with Web编程
Tagged with
comments powered by Disqus