[英]Application settings fom custom XML file, loading and error-handling
我正在处理一个使用静态类来存储从自定义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值读入每个对应的属性,如果为null则生成错误?
我试图像这样设计静态Settings类:
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字段”部分呢?
使用LINQ2XML ..它的酷
XELement doc=XElement.Load("yourXML.xml");
var LogList=doc.Descendants("configuration").Descendants("API").Descendants("log")
.Select(x=>
new
{
type=x.Element("type").Value;
location=x.Element("location").Value;
}
);
现在您可以使用for-each循环访问logList中的每个日志
foreach(var log in logList)
{
Console.WriteLine(log.type);
Console.WriteLine(log.location);
}
您也可以检查其是否为空
if(log.type==""){//its empty}
您可以使用XMLDocument / XPath。 像这样:
XmlDocument doc = new XmlDocument();
doc.Load("Settings.xml");
appSettings.LogType = doc.SelectSingleNode("/appSettings/configuration/API/log/type").InnerText;
实际上,我更喜欢使用序列化。 也许是标准序列化YAXLib ,它提供了一些有用的错误处理。
编辑:对我来说,它正在与InnerText。
我更喜欢个人使用XmlNodeList。
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Settings.xml");
// Get element from xml.
XmlNodeList type = xmlDoc.GetElementsByTagName("type");
// The following line assumes that there is only 1 type entry
appSettings.LogType = type[0].InnerText;
如果要获取多个条目,只需在for语句中打耳光即可。
for (int i = 0; i < type.Count; i++)
{
// Do stuff
appSettings.LogType = type[i].InnerText;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.