Freeform XML configuration section body in app.config

Is there a way to make a configuration section that allows you to create a free-form XML body? How can I get a free form body in code?

For example, I would like to create a ModuleConfigurationSection as follows:

<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> 

Thus, some code will deploy each of these types of modules from configuration sections using ConfigurationManager.GetSection("modules") , and I would like to pass the XML inside the moduleConfig element as an opaque configuration value for the module class constructor.

Any input is appreciated!

+7
c # configuration
source share
2 answers

Here is how I ended 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); } } 

So xml will look like this:

 <module name="ModuleA"> <config> <filePath>C:\files\file.foo</filePath> </config> </module> 

The body of the configuration item can be any free xml format you like. Assuming you created a collection when you execute ConfigurationManager.GetSection("modules") , you can access the Config property of each ModuleElement as an XElement representing the XML of the node configuration item.

+10
source share

In my application, I could not use the .NET 3.5 Framework. I used a slightly different approach and came up with this piece of code:

 public class ModuleSection : ConfigurationSection { private const string ELEMENT_NAME_CONFIG = "config"; private XmlNode _configNode; [ConfigurationProperty("name", IsRequired = true)] public string Name { get { return (string)base["name"]; } set { base["name"] = value; } } public XmlNode Config { get { return _configNode; } } protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader) { if(elementName.Equals(ELEMENT_NAME_CONFIG, StringComparison.Ordinal)) { // Add the unrecognized element. _configNode = _xmlDocument.ReadNode(reader); return true; } else { return base.OnDeserializeUnrecognizedElement(elementName, reader); } } } 
+1
source share

All Articles