2013-10-17 29 views
1

我發現一種方法可以從一個輸入文件構建一個字典,但它不會考慮多個輸入文件。爲了讓我的下一步努力:我希望將額外的輸入文件添加到現有的散列中,並嘗試不同的代碼,這個代碼與我希望完成的代碼有點接近,但它仍然缺少語法。試圖將多個XML輸入文件加載到iDictionary中<string,Ojbect>

 foreach (string file in filePaths) 
     { 
      XDocument xdoc = XDocument.Load(file); 

      allDict = (from m in xdoc.Descendants("msg") 
         .ToDictionary(m => m.Element("msgId").Value, 
             m => new msg 
             { 
             msgId = m.Element("msgId").Value, 
             msgType = m.Element("msgType").Value, 
             name = m.Element("name").Value 
             } 
      ) 
     } 

回答

0

創建一個「主」對象,然後附加從每個文件中獲得的值。

Dictionary<string, msg> masterDictionary = new Dictionary<string, mgs>(); 

foreach (string file in filePath) 
{ 
    XDocument xdoc = XDocument.Load(file); 
    Dictionary<string, msg> fileDictionary = xdoc 
     .Descendants("msg") 
     .ToDictionary(m => m.Element("msgId").Value, 
         m => new msg 
          { 
           msgId = m.Element("msgId").Value, 
           msgType = m.Element("msgType").Value, 
           name = m.Element("name").Value 
          }); 

    //now insert your new values into the master 
    foreach(var newValue in fileDictionary) 
     masterDictionary.Add(newValue.Key, newValue.Value); 
} 
+0

http://stackoverflow.com/questions/19416272/trying-to-load-multiple-xml-input-files-into-idictionarystring-ojbect – user2741445

+0

哇,第一部分工作順利,準確地工作正如我所希望的那樣。感謝您花時間回覆並節省了我的時間。順便說一句,有沒有你用來學習這個實現的參考,或者只是純粹的經驗?我仍然無法讓第二部分工作,即添加到主字典部分。它使用「System.NullReferenceException - 對象引用未設置爲對象的實例」在newValue.Value上崩潰。這可能與作爲對象的值而不是簡單類型有關。 – user2741445

+0

@ user2741445,沒問題。我從編程的所有時間開始就選擇了這種方法。至於你的錯誤,我不明白你是如何在那個地方得到一個空引用。 'newValue'不應該是'null'。 – gunr2171

相關問題