.net 是否可以在自定义配置节中使用任意XML?
假设我在ASP.NET web.config中定义了一个配置部分,如:.net 是否可以在自定义配置节中使用任意XML?,.net,asp.net,.net,Asp.net,假设我在ASP.NET web.config中定义了一个配置部分,如: <?xml version="1.0"?> <configuration> <configSections> <sectionGroup name="system.web"> <section name="MySettings" type="MyCompany.MyProject.Configuration.MySettings" allowLoc
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web">
<section name="MySettings" type="MyCompany.MyProject.Configuration.MySettings" allowLocation="true" allowDefinition="Everywhere" restartOnExternalChanges="false" />
</sectionGroup>
</configSections>
<system.web>
<MySettings knownProperty="some_value" unknownProperty="other_value" />
</system.web>
</configuration>
是否仍然可以运行应用程序而不会出现配置错误,并抱怨无法识别的属性“unknownProperty”
另外,如果可能的话,我也可以用一种方法捕捉错误并忽略它
换句话说,我希望XML有一个属性,该属性在它绑定到的匹配类型中没有定义。可以在现有配置API的范围内完成吗?我很确定这是可能的,因为一些内置部分,如WCF和membership,可以毫无错误地完成这项工作。OnDezedAttribute是否满足您的需要
protected override bool OnDeserializeUnrecognizedAttribute(string name, string value){
//don't call base to avoid error
}
我正在使用下面的代码成功地从web.config ASP文件中读取任何XML结构。请注意,仅支持读取
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;
/* In this file, you'll find an example on how to store an custom section in an .Net
* application configuration file that can contains arbitrary XML that can be retrieved
* as a raw System.Xml.XmlNode. In the specific example below, I wanted to be able to
* store arbitrary information about POP servers I retrieve email from, without having to
* write specific Configuration data for each different case. This is usefull for quick
* application development.
*/
/* Config file sample :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="MySection">
<section name="MailRetrieve" type="ConsoleApplication1.MailRetrieveConfigurationSection, ConsoleApplication1"/>
</sectionGroup>
</configSections>
<MySection>
<MailRetrieve>
<Hosts>
<add username="projects@domain.com" popserver="mail.domain.com" password="1234">
<RawXml>
<AnElement>Arbitrary string one</AnElement>
</RawXml>
</add>
<add username="tasks@domain.com" popserver="mail.domain.com" password="1234"></add>
<add username="bugs@domain.com" popserver="mail.domain.com" password="1234" >
<RawXml>
<OtherElement>Arbitrary string two</OtherElement>
</RawXml>
</add>
</Hosts>
</MailRetrieve>
</MySection>
</configuration>
*/
/* Sample output : running the piece of code below, using config file above, gives :
Custom XML for projects@domain.com__@__mail.domain.com:
<RawXml><AnElement>Arbitrary string one</AnElement></RawXml>
************
Custom XML for tasks@domain.com__@__mail.domain.com:
- none -
************
Custom XML for bugs@domain.com__@__mail.domain.com:
<RawXml><OtherElement>Arbitrary string two</OtherElement></RawXml>
--> Found OtherElement !
************
Hit a key to finish
*/
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
MailRetrieveConfigurationSection config = (MailRetrieveConfigurationSection)
(System.Configuration.ConfigurationManager.GetSection("MySection/MailRetrieve"));
if (config != null) {
foreach (HostConfigElement cfg in config.Hosts) {
System.Console.WriteLine("Custom XML for " + cfg.PopMailboxID + ":");
if (cfg.RawXml.Node != null) {
System.Console.WriteLine(cfg.RawXml.Node.OuterXml);
if (cfg.RawXml.Node.SelectSingleNode("OtherElement") != null) {
Console.WriteLine("--> Found OtherElement !");
}
}
else {
System.Console.WriteLine(" - none -");
}
System.Console.WriteLine("************");
}
}
System.Console.WriteLine("Hit a key to finish");
System.Console.ReadKey();
}
}
public class MailRetrieveConfigurationSection : ConfigurationSection {
[ConfigurationProperty("Hosts")]
public MailRetrieveHostsConfigCollection Hosts {
get {
return ((MailRetrieveHostsConfigCollection)(base["Hosts"]));
}
}
}
[ConfigurationCollectionAttribute(typeof(HostConfigElement))]
public class MailRetrieveHostsConfigCollection : ConfigurationElementCollection {
protected override ConfigurationElement CreateNewElement() {
return new HostConfigElement();
}
/// <summary>
/// We want to have only one configuration per POP mailbox, wich key is host+username
/// If more configuration is wanted, one must introduce an "id" attribute.
/// </summary>
protected override object GetElementKey(ConfigurationElement element) {
return ((HostConfigElement)(element)).PopMailboxID;
}
public void Add(HostConfigElement element) {
this.BaseAdd(element);
}
public void Remove(string key) {
this.BaseRemove(key);
}
public void Clear() {
this.BaseClear();
}
public HostConfigElement this[int idx] {
get { return (HostConfigElement)this[idx]; }
}
}
public class MyCustomConfigurationElement : ConfigurationElement {
public XmlNode Node = null;
protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey) {
XmlDocument doc = new XmlDocument();
doc.Load(reader.ReadSubtree());
Node = doc.FirstChild;
}
}
public class HostConfigElement : ConfigurationElement {
/// <summary>
/// A POP3 mailbox is distinguished from another using the server name and user name.
/// </summary>
public string PopMailboxID {
get {
return Username + "__@__" + PopServer; //
}
}
[ConfigurationProperty("popserver", DefaultValue = "", IsRequired = true)]
public string PopServer {
get { return (string)this["popserver"]; }
set { this["popserver"] = value; }
}
[ConfigurationProperty("username", IsRequired = true, Options = ConfigurationPropertyOptions.IsKey)]
public string Username {
get { return (string)this["username"]; }
set { this["username"] = value; }
}
[ConfigurationProperty("password", DefaultValue = "", IsRequired = true)]
public string Password {
get { return (string)this["password"]; }
set { this["password"] = value; }
}
[ConfigurationProperty("RawXml", IsRequired=false)]
public MyCustomConfigurationElement RawXml {
get { return (MyCustomConfigurationElement)this["RawXml"]; }
set { this["RawXml"] = value; }
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统文本;
使用系统配置;
使用System.Xml;
/*在这个文件中,您将看到一个关于如何在.Net中存储自定义节的示例
*可包含可检索的任意XML的应用程序配置文件
*作为原始System.Xml.XmlNode。在下面的具体示例中,我希望能够
*存储有关我从中检索电子邮件的POP服务器的任意信息,而无需
*为每个不同的情况编写特定的配置数据。这是有用的快速
*应用程序开发。
*/
/*配置文件示例:
任意字符串1
任意字符串二
*/
/*示例输出:使用上面的配置文件运行下面的代码段,得到:
用于projects@domain.com__@__mail.domain.com:
任意字符串1
************
用于tasks@domain.com__@__mail.domain.com:
-没有-
************
用于bugs@domain.com__@__mail.domain.com:
任意字符串二
-->找到其他元素!
************
按一个键完成
*/
命名空间控制台应用程序1{
班级计划{
静态void Main(字符串[]参数){
MailRetrieveConfiguration节配置=(MailRetrieveConfiguration节)
(System.Configuration.ConfigurationManager.GetSection(“MySection/MailRetrieve”);
如果(配置!=null){
foreach(config.Hosts中的HostConfigElement cfg){
System.Console.WriteLine(“用于“+cfg.PopMailboxID+”:”)的自定义XML;
如果(cfg.RawXml.Node!=null){
System.Console.WriteLine(cfg.RawXml.Node.OuterXml);
if(cfg.RawXml.Node.SelectSingleNode(“OtherElement”)!=null){
WriteLine(“-->Found OtherElement!”);
}
}
否则{
System.Console.WriteLine(“-none-”);
}
System.Console.WriteLine(“*************”);
}
}
System.Console.WriteLine(“点击一个键完成”);
System.Console.ReadKey();
}
}
公共类MailRetrieveConfiguration节:配置节{
[配置属性(“主机”)]
公用邮件检索主机配置收集主机{
得到{
返回((MailRetrieveHostsConfigCollection)(基本[“主机]);
}
}
}
[ConfigurationCollectionAttribute(类型(HostConfigElement))]
公共类MailRetrieveHostsConfigCollection:ConfigurationElementCollection{
受保护的覆盖ConfigurationElement CreateNewElement(){
返回新的HostConfigElement();
}
///
///我们希望每个POP邮箱只有一个配置,其密钥为主机+用户名
///如果需要更多配置,则必须引入“id”属性。
///
受保护的覆盖对象GetElementKey(ConfigurationElement元素){
返回((HostConfigElement)(element)).PopMailboxID;
}
公共无效添加(HostConfigElement元素){
此.BaseAdd(元素);
}
公共无效删除(字符串键){
此.BaseRemove(键);
}
公共空间清除(){
这个。BaseClear();
}
public HostConfigElement此[int idx]{
获取{return(HostConfigElement)this[idx];}
}
}
公共类MyCustomConfigurationElement:ConfigurationElement{
公共XmlNode=null;
受保护的重写void反序列化元素(XmlReader reader,bool serializeCollectionKey){
XmlDocument doc=新的XmlDocument();
doc.Load(reader.ReadSubtree());
Node=doc.FirstChild;
}
}
公共类HostConfigElement:ConfigurationElement{
///
///使用服务器名和用户名将POP3邮箱与其他邮箱区分开来。
///
公共字符串PopMailboxID{
得到{
返回用户名+“\@”+PopServer//
}
}
[ConfigurationProperty(“popserver”,DefaultValue=“”,IsRequired=true)]
公共字符串服务器{
获取{return(string)this[“popserver”];}
设置{this[“popserver”]=value;}
}
[ConfigurationProperty(“用户名”,IsRequired=true,Options=ConfigurationPropertyOptions.IsKey)]
公共字符串用户名{
获取{return(string)this[“username”];}
设置{this[“username”]=value;}
}
[ConfigurationP
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;
/* In this file, you'll find an example on how to store an custom section in an .Net
* application configuration file that can contains arbitrary XML that can be retrieved
* as a raw System.Xml.XmlNode. In the specific example below, I wanted to be able to
* store arbitrary information about POP servers I retrieve email from, without having to
* write specific Configuration data for each different case. This is usefull for quick
* application development.
*/
/* Config file sample :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="MySection">
<section name="MailRetrieve" type="ConsoleApplication1.MailRetrieveConfigurationSection, ConsoleApplication1"/>
</sectionGroup>
</configSections>
<MySection>
<MailRetrieve>
<Hosts>
<add username="projects@domain.com" popserver="mail.domain.com" password="1234">
<RawXml>
<AnElement>Arbitrary string one</AnElement>
</RawXml>
</add>
<add username="tasks@domain.com" popserver="mail.domain.com" password="1234"></add>
<add username="bugs@domain.com" popserver="mail.domain.com" password="1234" >
<RawXml>
<OtherElement>Arbitrary string two</OtherElement>
</RawXml>
</add>
</Hosts>
</MailRetrieve>
</MySection>
</configuration>
*/
/* Sample output : running the piece of code below, using config file above, gives :
Custom XML for projects@domain.com__@__mail.domain.com:
<RawXml><AnElement>Arbitrary string one</AnElement></RawXml>
************
Custom XML for tasks@domain.com__@__mail.domain.com:
- none -
************
Custom XML for bugs@domain.com__@__mail.domain.com:
<RawXml><OtherElement>Arbitrary string two</OtherElement></RawXml>
--> Found OtherElement !
************
Hit a key to finish
*/
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
MailRetrieveConfigurationSection config = (MailRetrieveConfigurationSection)
(System.Configuration.ConfigurationManager.GetSection("MySection/MailRetrieve"));
if (config != null) {
foreach (HostConfigElement cfg in config.Hosts) {
System.Console.WriteLine("Custom XML for " + cfg.PopMailboxID + ":");
if (cfg.RawXml.Node != null) {
System.Console.WriteLine(cfg.RawXml.Node.OuterXml);
if (cfg.RawXml.Node.SelectSingleNode("OtherElement") != null) {
Console.WriteLine("--> Found OtherElement !");
}
}
else {
System.Console.WriteLine(" - none -");
}
System.Console.WriteLine("************");
}
}
System.Console.WriteLine("Hit a key to finish");
System.Console.ReadKey();
}
}
public class MailRetrieveConfigurationSection : ConfigurationSection {
[ConfigurationProperty("Hosts")]
public MailRetrieveHostsConfigCollection Hosts {
get {
return ((MailRetrieveHostsConfigCollection)(base["Hosts"]));
}
}
}
[ConfigurationCollectionAttribute(typeof(HostConfigElement))]
public class MailRetrieveHostsConfigCollection : ConfigurationElementCollection {
protected override ConfigurationElement CreateNewElement() {
return new HostConfigElement();
}
/// <summary>
/// We want to have only one configuration per POP mailbox, wich key is host+username
/// If more configuration is wanted, one must introduce an "id" attribute.
/// </summary>
protected override object GetElementKey(ConfigurationElement element) {
return ((HostConfigElement)(element)).PopMailboxID;
}
public void Add(HostConfigElement element) {
this.BaseAdd(element);
}
public void Remove(string key) {
this.BaseRemove(key);
}
public void Clear() {
this.BaseClear();
}
public HostConfigElement this[int idx] {
get { return (HostConfigElement)this[idx]; }
}
}
public class MyCustomConfigurationElement : ConfigurationElement {
public XmlNode Node = null;
protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey) {
XmlDocument doc = new XmlDocument();
doc.Load(reader.ReadSubtree());
Node = doc.FirstChild;
}
}
public class HostConfigElement : ConfigurationElement {
/// <summary>
/// A POP3 mailbox is distinguished from another using the server name and user name.
/// </summary>
public string PopMailboxID {
get {
return Username + "__@__" + PopServer; //
}
}
[ConfigurationProperty("popserver", DefaultValue = "", IsRequired = true)]
public string PopServer {
get { return (string)this["popserver"]; }
set { this["popserver"] = value; }
}
[ConfigurationProperty("username", IsRequired = true, Options = ConfigurationPropertyOptions.IsKey)]
public string Username {
get { return (string)this["username"]; }
set { this["username"] = value; }
}
[ConfigurationProperty("password", DefaultValue = "", IsRequired = true)]
public string Password {
get { return (string)this["password"]; }
set { this["password"] = value; }
}
[ConfigurationProperty("RawXml", IsRequired=false)]
public MyCustomConfigurationElement RawXml {
get { return (MyCustomConfigurationElement)this["RawXml"]; }
set { this["RawXml"] = value; }
}
}
}
protected override bool OnDeserializeUnrecognizedAttribute(string name, string value) {
try {
var lProperty = new ConfigurationProperty(name, typeof(String));
Properties.Add(lProperty);
base[name] = value;
return true;
} catch {
return false;
}
}
public class XmlConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("xml", IsRequired = false)]
public XmlElement Xml
{
get { return (XmlElement)this["xml"]; }
set { this["xml"] = value; }
}
}
public class XmlElement : ConfigurationElement
{
public XmlNode Node = null;
protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
{
XmlDocument doc = new XmlDocument();
doc.Load(reader.ReadSubtree());
Node = doc.FirstChild;
}
}
var xml = (System.Configuration.ConfigurationManager.GetSection("xmlSettings") as XmlConfigurationSection).Xml;
<configuration>
<configSections>
<section name="xmlSettings" type="WebApp.XmlConfigurationSection" />
</configSections>
<xmlSettings>
<xml>
<anyxmlroot>...</anyxmlroot>
</xml>
</xmlSettings>
</configuration>