【发布时间】:2011-10-26 07:10:23
【问题描述】:
我有一个班级负责读取和保存 XML 文件。 现在它的一个简单版本如下所示:
public class EstEIDPersoConfig
{
public bool LaunchDebugger { get ; set; }
public string Password { get; set; }
public int Slot { get; set; }
public string Reader { get; set; }
public string TestInput { get; set; }
public bool Logging { get; set; }
public EstEIDPersoConfig()
{
XElement xml = XElement.Load(myxml.xml);
XElement Configuration = xml.Element("Configuration");
LaunchDebugger = Convert.ToBoolean(Configuration.Element("LaunchDebugger").Value);
Password = Configuration.Element("Password").Value;
Slot = Convert.ToInt32(Configuration.Element("Slot").Value);
Reader = Configuration.Element("Reader").Value;
TestInput = Configuration.Element("TestInput").Value;
Logging = Convert.ToBoolean(Configuration.Element("Logging").Value);
}
}
以后还会有更多。所以问题是如果xml中不存在某些元素,我会得到System.NullReferenceException。所以我需要检查元素是否为null。这是一种方法:
var value = Configuration.Element("LaunchDebugger").Value;
if (value != null)
LaunchDebugger = Convert.ToBoolean(value);
else
throw new Exception("LaunchDebugger element missing from xml!");
但是对每个元素都这样做就太过分了。所以我需要一些好的想法来简化这个系统,这样它就不会变成 1000 行代码。
编辑:编辑最后一个代码sn-p,想法不是设置默认值,想法是通知用户xml中缺少此元素whats null。
【问题讨论】:
-
当 xml 的值为 null 时,对相应的构造函数执行所谓的 xml 惰性初始化。
-
@hs2d - 我认为 abatishchev 的答案正是您想要的。
标签: c# .net xml linq-to-xml