【发布时间】:2012-10-05 14:17:38
【问题描述】:
我正在开发一个遗留应用程序,它使用静态类来存储从自定义 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 字段”部分?
【问题讨论】:
-
您不只是在标记为可序列化的设置类上使用标准 XML 序列化的任何原因?您可能需要对 null 属性进行一些额外的错误检查,但这也有些微不足道。
-
@WonkotheSane 不幸的是,我对 XML 序列化的了解有限。你有一个好的教程的链接吗?
-
只是谷歌的“XML 序列化 C#”。如果今晚晚些时候我有机会在这里举个例子,我会的,但是网上有很多例子。
-
xml 日志是否只包含 1 个日志