2011-09-25 128 views
0

我想從不同的機器讀取XML文件,其中一些文件可能具有其他人不具備的數據元素。目前,我正在使用Try-Catch塊來處理這些情況,但我想知道是否有更好的方法來做到這一點,有什麼想法?XML文件中缺少XML元素

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 { } 
    } 

好吧,我想通了,根據約翰·桑德斯後一種解決方案:

 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塊現在看起來如此。

回答

2

這是「處理」問題的可怕方法。如果XML可能合法缺少元素,則在嘗試訪問它們之前檢查元素是否存在。

你空的catch塊忽略它們發生的內部,這意味着該元素缺失不只是例外所有例外。


一旦表被加載,列就會出現或不出現。您可以使用ds.Tables[config.GlobalVars.Paths].Columns.Contains("columnName")來確定列是否存在。

如果存在一個列,那麼對於任何給定的行,列可以是或不可以是空的。使用drv.Row.IsNull("columnName")來確定該行中的該列是否爲空。

+0

謝謝,我想這是目的我最初的帖子,我正在尋找更有效地做到這一點的方法。你能解釋一下在訪問它們之前如何檢查元素嗎? –

+0

@@ John - 我實際上正在檢查列的長度屬性:if(drv [「SuspressMessages」]。ToString()。Length> 0)。我應該檢查它是否爲空嗎? –

+1

是的,檢查null更接近NULL的數據庫概念。此外,請記住該列可能不存在(在這種情況下,'[「columnName」]'將失敗),或者可能包含一個'null'值(在這種情況下'.ToString()'將失敗)。 –

0

好吧,我只注意到的XmlDataDocument將要很快過時,所以我決定刮掉,並使用LINQ到XML,這裏是我的新sopultion

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(); 
      } 
     }