我正在尝试从不同的计算机读取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块现在看起来是什么样子。
发布于 2011-09-25 23:44:53
这是一种可怕的“处理”问题的方式。如果XML可能合法地缺少元素,那么在尝试访问这些元素之前,请检查这些元素是否存在。
空的catch块会忽略它们内部发生的所有异常,而不仅仅是意味着元素丢失的异常。
一旦装载了表,这些列就存在或不存在。您可以使用ds.Tables[config.GlobalVars.Paths].Columns.Contains("columnName")来确定列是否存在。
如果列存在,则对于任何给定行,该列可能为null,也可能不为null。使用drv.Row.IsNull("columnName")确定该行中的列是否为null。
发布于 2011-09-27 04:52:24
好了,我刚刚注意到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();
}
}https://stackoverflow.com/questions/7546532
复制相似问题