我正在尝试编写一个保持与XML文件同步的类IXmlSerializable
。 XML文件的格式如下:使用C#同步类和文件之间的XML节点
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<logging>
<logLevel>Error</logLevel>
</logging>
...potentially other sections...
</configuration>
我有一个DllConfig
类整个XML文件和LoggingSection
类代表<logging>
及其内容,即<logLevel>
。 DllConfig
拥有此属性:
[XmlElement(ElementName = LOGGING_TAG_NAME,
DataType = "LoggingSection")]
public LoggingSection Logging { get; protected set; }
我要的是为后盾的XML文件进行更新(即重写)当一个属性设置。当已设置Logging
时,我已经有DllConfig
。但是,当Logging.LogLevel
被设置时,我应该如何去做这件事?下面是我的意思的例子:
var config = new DllConfig("path_to_backing_file.xml");
config.Logging.LogLevel = LogLevel.Information; // not using Logging setter, but a
// setter on LoggingSection, so how
// does path_to_backing_file.xml
// have its contents updated?
我目前的解决方案是有一个SyncedLoggingSection
类,从LoggingSection
继承并在构造函数中需要DllConfig
实例。它声明一个new LogLevel
,它在设置时更新基类中的LogLevel
,并使用给定的DllConfig
将整个DllConfig
写出到支持XML文件。这是一个很好的技术吗?
我不认为我可以将SyncedLoggingSection
自己序列化到支持XML文件,因为并非所有内容都将被写入,只是<logging>
节点。然后,我会最终得到一个XML文件,其中只包含<logging>
部分及其更新的<logLevel>
,而不是更新的整个配置文件<logLevel>
。因此,我需要将DllConfig
的实例传递给SyncedLoggingSection
。
看起来几乎就像我想的事件处理程序,一个在DllConfig
当特殊属性(即LogLevel
)在其属性(即Logging
)进行设置,将另行通知。这样的事情可能吗?
莎拉,有没有一个原因,你不只是在'System.Configuration'命名空间中使用标准类型? – 2010-06-16 19:04:58
@John:你是指在Visual Studio中使用app.config和automagical Config.settings? – 2010-06-16 19:07:51
我正在讨论如何根据情况创建可以在app.config或web.config中使用的自定义配置节。您可以使用标准机制将更改写回文件。请参阅文档中的[ConfigurationManager类](http://msdn.microsoft.com/zh-cn/library/system.configuration.configurationmanager.aspx)。 – 2010-06-16 19:38:55