问题描述
有没有一种方法,使配置部分,将允许自由形式的XML的身体吗? ?我该如何获得在代码自由身。
Is there a way to make a configuration section that would allow a freeform XML body? How would I get that freeform body in code?
例如我想创建这样一个ModuleConfigurationSection:
For example I'd like to create a ModuleConfigurationSection like this:
<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(模块)
,我想通过的ModuleConfig
元素中的XML作为一个不透明的配置值的构造模块类。
So some code would spin up each of these module types from config sections using ConfigurationManager.GetSection("modules")
and I'd like to pass the XML inside the moduleConfig
element as an opaque configuration value to the constructor of the module class.
任何输入赞赏!
推荐答案
这是我怎么会办成这样的:
This is how I ended up accomplishing this:
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看起来像:
So the xml would look like:
<module name="ModuleA">
<config>
<filePath>C:\files\file.foo</filePath>
</config>
</module>
的
配置元素的主体可能是你喜欢的任何自由的XML。假设你建立了一个集合,当你做 ConfigurationManager.GetSection(模块)
然后你可以访问配置
每个 ModuleElement
对象代表的配置元素节点的XML一个的XElement的属性。
The body of the config element could be any freeform xml that you like. Assuming that you set up a collection, when you do ConfigurationManager.GetSection("modules")
you can then access the Config
property of each ModuleElement
object as an XElement representing the XML of the config element node.
这篇关于自由形式的XML配置部分身体的app.config的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!