I’m working on a legacy application that uses a static class to store settings that are read from a custom XML file.
However, as part of a slight upgrade to the module, the customer would like to see, at runtime, which fields are missing.
Consider the following Settings.xml file:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<configuration>
<API>
<log>
<type>09</type>
<location>C:\Test\Test.log</filename>
</log>
</API>
</configuration>
</appSettings>
The settings are currently read into the static class using an XMLReader (seen below):
using (XmlTextReader xmlReader = new XmlTextReader("Settings.xml"))
{
xmlReader.ReadToFollowing("API");
xmlReader.ReadToFollowing("log");
xmlReader.ReadToFollowing("type");
this.logtype = xmlReader.ReadElementContentAsString();
//snip...
}
This same code is used to read each and every setting. There has to be a better way. Is there any way that I can read the XML values into each corresponding property, and generate an error if it’s null?
I’m attempting to design the static Settings class as such:
public static class Settings
{
private static string logtype
public static string LogType
{
get
{ return logtype; }
set
{ logtype = value; }
}
}
And then use something like the following to “grab” the values:
public static void initSettings()
{
appSettings.LogType = read the configuration\API\log\type field from xml;
}
I’m pretty sure that I’d just check for the null character in the property constructor, but how would I do the ‘read the configuration\API\log\type field from xml’ part of the initSettings method?
You could use XMLDocument / XPath. Something like this:
Actually I would prefer to use Serialization. Maybe the standard serialization a YAXLib, which provides some useful error handling.
Edit: For me it’s working with InnerText.