我正在开发一个遗留应用程序,该应用程序使用静态类来存储从自定义 XML 文件中读取的设置。但是,作为对模块的轻微升级的一部分,客户希望在运行时查看缺少哪些字段。
考虑以下 Settings.xml 文件:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<configuration>
<API>
<log>
<type>09</type>
<location>C:\Test\Test.log</filename>
</log>
</API>
</configuration>
</appSettings>
当前使用 XMLReader 将设置读入静态类(如下所示):
using (XmlTextReader xmlReader = new XmlTextReader("Settings.xml"))
{
xmlReader.ReadToFollowing("API");
xmlReader.ReadToFollowing("log");
xmlReader.ReadToFollowing("type");
this.logtype = xmlReader.ReadElementContentAsString();
//snip...
}
相同的代码用于读取每个设置。一定有更好的方法。有什么方法可以将 XML 值读入每个相应的属性,如果它为空则生成错误?
我正在尝试这样设计静态设置类:
public static class Settings
{
private static string logtype
public static string LogType
{
get
{ return logtype; }
set
{ logtype = value; }
}
}
然后使用类似下面的东西来“抓取”这些值:
public static void initSettings()
{
appSettings.LogType = read the configuration\API\log\type field from xml;
}
我很确定我只是在属性构造函数中检查空字符,但是我将如何执行 initSettings 方法的“从 xml 读取 configuration\API\log\type 字段”部分?