有没有办法建立一个允许自由形式的
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:\files\file.foo</filePath> </config> </module>
config元素的主体可以是您喜欢的任何自由形式的xml.假设您设置了一个集合,当您执行ConfigurationManager.GetSection(“modules”)时,您可以访问每个ModuleElement对象的Config属性作为表示config元素节点的XML的XElement.
原文地址:https://www.jb51.cc/csharp/100913.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。