c# – app.config中的自由格式XML配置部分主体
发布时间:2020-12-15 08:09:15 所属栏目:百科 来源:网络整理
导读:有没有办法建立一个允许自由形式的 XML体的配置部分?我如何在代码中获得自由形式的主体? 例如,我想像这样创建一个ModuleConfigurationSection: modules module name="ModuleA" type="My.Namespace.ModuleA,My.Assembly" moduleConfig serviceAddresshttp:
有没有办法建立一个允许自由形式的
XML体的配置部分?我如何在代码中获得自由形式的主体?
例如,我想像这样创建一个ModuleConfigurationSection: <modules> <module name="ModuleA" type="My.Namespace.ModuleA,My.Assembly"> <moduleConfig> <serviceAddress>http://myserver/myservice.svc</serviceAddress> </moduleConfig> </module> <module name="ModuleB" type="My.Namespace.ModuleB,My.OtherAssembly"> <moduleConfig> <filePath>c:directory</filePath> </moduleConfig> </module> </modules> 因此,一些代码会使用ConfigurationManager.GetSection(“modules”)从配置节中调出每个模块类型,并且我想将moduleConfig元素中的XML作为opaque配置值传递给模块类的构造函数. 任何输入赞赏! 解决方法
这就是我最终完成此任务的方式:
public class ModuleElement : ConfigurationElement { [ConfigurationProperty("name",IsRequired = true)] public string Name { get { return (string)base["name"]; } set { base["name"] = value; } } XElement _config; public XElement Config { get { return _config; } } protected override bool OnDeserializeUnrecognizedElement(string elementName,System.Xml.XmlReader reader) { if (elementName == "config") { _config = (XElement)XElement.ReadFrom(reader); return true; } else return base.OnDeserializeUnrecognizedElement(elementName,reader); } } 所以xml看起来像: <module name="ModuleA"> <config> <filePath>C:filesfile.foo</filePath> </config> </module> config元素的主体可以是您喜欢的任何自由形式的xml.假设您设置了一个集合,当您执行ConfigurationManager.GetSection(“modules”)时,您可以访问每个ModuleElement对象的Config属性作为表示config元素节点的XML的XElement. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |