0

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

4

2 回答 2

3

这是一种“处理”问题的可怕方式。如果 XML 可能合法地缺少元素,则在尝试访问它们之前检查这些元素是否存在。

您的空 catch 块会忽略其中发生的所有异常,而不仅仅是表示元素丢失的异常。


加载表后,列是否存在。您可以使用ds.Tables[config.GlobalVars.Paths].Columns.Contains("columnName")来确定该列是否存在。

如果存在列,则对于任何给定行,该列可能为空,也可能不为空。用于drv.Row.IsNull("columnName")确定该行中的该列是否为空。

于 2011-09-25T15:44:52.567 回答
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();
            }
        }
于 2011-09-26T20:52:24.237 回答