synchronizing XML nodes between class and file using C#
Posted
by Sarah Vessels
on Stack Overflow
See other posts from Stack Overflow
or by Sarah Vessels
Published on 2010-06-16T18:45:39Z
Indexed on
2010/06/16
19:02 UTC
Read the original article
Hit count: 378
I'm trying to write an IXmlSerializable
class that stays synced with an XML file. The XML file has the following format:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<logging>
<logLevel>Error</logLevel>
</logging>
...potentially other sections...
</configuration>
I have a DllConfig
class for the whole XML file and a LoggingSection
class for representing <logging>
and its contents, i.e., <logLevel>
. DllConfig
has this property:
[XmlElement(ElementName = LOGGING_TAG_NAME,
DataType = "LoggingSection")]
public LoggingSection Logging { get; protected set; }
What I want is for the backing XML file to be updated (i.e., rewritten) when a property is set. I already have DllConfig
do this when Logging
is set. However, how should I go about doing this when Logging.LogLevel
is set? Here's an example of what I mean:
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?
My current solution is to have a SyncedLoggingSection
class that inherits from LoggingSection
and also takes a DllConfig
instance in the constructor. It declares a new LogLevel
that, when set, updates the LogLevel
in the base class and also uses the given DllConfig
to write the entire DllConfig
out to the backing XML file. Is this a good technique?
I don't think I can just serialize SyncedLoggingSection
by itself to the backing XML file, because not all of the contents will be written, just the <logging>
node. Then I'd end up with an XML file containing only the <logging>
section with its updated <logLevel>
, instead of the entire config file with <logLevel>
updated. Hence, I need to pass an instance of DllConfig
to SyncedLoggingSection
.
It seems almost like I want an event handler, one in DllConfig
that would notice when particular properties (i.e., LogLevel
) in its properties (i.e., Logging
) were set. Is such a thing possible?
© Stack Overflow or respective owner