我正在尝试从不同的机器读取 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 块现在的样子。