我正在尝试从不同的计算机读取XML文件,其中一些文件可能包含其他人没有的数据元素。目前,我正在使用Try-Catch块来处理这些情况,但我想知道是否有更好的方法来做这个,有什么想法吗?
XmlDataDocument xmlDatadoc = new XmlDataDocument();
xmlDatadoc.DataSet.ReadXml("MachineData.xml");
DataSet ds = new DataSet("AppData");
ds = xmlDatadoc.DataSet;
DataView dv = new DataView(ds.Tables[config.GlobalVars.Paths]);
foreach (DataRowView drv in dv)
{
try
{
cApp.TransferProtcol = drv["TransferProtocol"].ToString();
}
catch { }
try
{
cApp.RemoteServerPath = drv["RemoteServer"].ToString();
}
catch { }
}
好的,我找到了一个基于John Saunders帖子的解决方案:
if(ds.Tables[0].Columns.Contains("TransferProtocol")
{
try
{
if (drv["TransferProtocol"].ToString().Length > 0)
{
cApp.TransferProtcol = drv["TransferProtocol"].ToString();
}
}
catch(Exception e)
{
Messagebox.Show(e.Message);
}
}
我同意空的Catch块,但我将它们存在以用于测试目的。我已经编辑了我的帖子,看看我的Try-Catch块现在看起来是什么。
答案 0 :(得分:2)
这是一种“处理”问题的可怕方式。如果XML可能合法地缺少元素,那么在尝试访问它们之前检查元素是否存在。
您的空catch块会忽略在其中发生的所有异常,而不仅仅是表示缺少该元素的异常。
加载表后,列是否存在。您可以使用ds.Tables[config.GlobalVars.Paths].Columns.Contains("columnName")
来确定列是否存在。
如果列存在,则对于任何给定的行,该列可能为空,也可能不为空。使用drv.Row.IsNull("columnName")
确定该行中的该列是否为空。
答案 1 :(得分:0)
好吧,我刚刚注意到XmlDataDocument很快就会被弃用,所以我决定将它删除并使用Linq to XML,这是我的新发明
public List<cApplication> GetAppSettings()
{
if (!File.Exists(Config.System.XMLFilePath))
{
WriteXMLFile();
}
try
{
XDocument data = XDocument.Load(Config.System.XMLFilePath);
return (from c in data.Descendants("Application")
orderby c.Attribute("Name")
select new cApplication()
{
LocalVersion = (c!=null)?c.Element("Version").Value:string.Empty,
RemoteVersion = (c!=null)?c.Element("RemoteVersion").Value:string.Empty,
DisableApp = (c!=null)?((YesNo)Enum.Parse(typeof(YesNo), c.Element("DisableApplication").Value, true)):YesNo.No,
SuspressMessages = (c != null) ? ((YesNo)Enum.Parse(typeof(YesNo), c.Element("SuspressMessage").Value, true)):YesNo.No
}).ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
List<cApplication> l = new List<cApplication>().ToList();
return l.ToList();
}
}