如何获取配置元素
直升机
谁能解释我如何从.config文件中获取配置元素。 我知道如何处理属性而不是元素。 例如,我想解析以下内容:
<![CDATA[ .... ]]> ....
到目前为止,我的c#代码看起来像这样:
public class MyConfiguration : ConfigurationSection { [ConfigurationProperty("enabled", DefaultValue = "true")] public bool Enabled { get { return this["enabled"].ToString().ToLower() == "true" ? true : false; } } [ConfigurationProperty("header")] public string header { ??? } }
它适用于属性,如何处理元素(上面代码中的标题属性)?
还有另一种方法可以做同样的事情。
我们可以通过重写DeserializeElement
方法来获取字符串值来创建元素:
public class EmailTextElement : ConfigurationElement { public string Value { get; private set; } protected override void DeserializeElement(XmlReader reader, bool s) { Value = reader.ReadElementContentAs(typeof(string), null) as string; } }
这是一个非常好的自定义配置部分设计工具,你可以使用(它是免费的):
配置部分设计器
编辑:
我正在研究MSDN,似乎自定义配置部分无法做你想要的,即。 从元素获取配置值。 自定义配置元素可以包含其他配置元素,但配置值始终来自属性。
也许你可以将你的html片段放到其他文件中并从配置中引用它们,就像这样。
inheritanceConfigurationElement类并覆盖其deserialize方法。 使用新类来表示具有文本内容的元素。
http://www.codeproject.com/KB/XML/ConfigurationTextElement.aspx
使用您的示例,您将覆盖ConfigurationElement中“header”的反序列化以获取CDATA值。
....
您可以使用ConfigurationManager.GetSection(“SectionName”)方法获取配置文件中的配置部分。
我终于找到了一种方法。
有IConfigurationSectionHandler接口,允许我想要的东西。 它需要一个人来编写方法
public object Create(object parent, object configContext, XmlNode section)
在它之后,你自己解析部分 ,所以我能够没有问题地获取XmlElement:
header = s["header"] != null ? s["header"].InnerText : String.Empty; title = s["title"] != null ? s["title"].InnerText : String.Empty;
这方面的缺点是接口已过时,但MSDN声明它不会从框架的未来版本中删除,因为它在内部使用。
您可以创建一个inheritance自System.Configuration.ConfigurationElement的类,该类表示配置节中的元素。
ConfigurationElement的MSDN文档中有一个简单的示例。
根据MSDN ,在.NET 4中有一个新的CurrentConfiguration
属性,它提供了对顶级Configuration
实例的引用,该实例表示当前ConfigurationElement
实例所属的配置层次结构。