2014-04-09 28 views
0

讀取XML我有這樣一個XML文件:錯誤而在字典

<APICollection><API name="myapiName" message="myAPIMessage" /></APICollection> 

當我試圖在這樣的詞典閱讀本:

Dictionary<string,string> apiMap = new Dictionary<string,string>();  
XDocument xdoc = XDocument.Load(path);  
apiMap = xdoc.Root.Elements() 
       .ToDictionary(a => (string)a.Attribute("apiName"), a => (string)a.Attribute("apiMessage")); 

一切都很正常。但是,如果我有相同的密鑰(名稱)的多個條目,我得到一個通用的例外是這樣的:

An item with the same key has already been added. 

我不知道我能做些什麼來修改錯誤消息至少給了哪個鍵存在多個倍。任何人都可以幫忙嗎?

感謝,

Harit

回答

1

我建議不要直接創建字典,而是爲重複鍵第一次檢查是這樣的:

XDocument xdoc = XDocument.Load(path);  
var apiMap = xdoc.Root.Elements() 
       .Select(a => new 
        { 
         ApiName = (string)a.Attribute("apiName"), 
         ApiMessage = (string)a.Attribute("apiMessage") 
        }); 
var duplicateKeys = (from x in apiMap 
        group x by x.ApiName into g 
        select new { ApiName = g.Key, Cnt = g.Count() }) 
        .Where(x => x.Cnt > 1) 
        .Select(x => x.ApiName); 
if (duplicateKeys.Count() > 0) 
    throw new InvalidOperationException("The following keys are present more than once: " 
      + string.Join(", ", duplicateKeys)); 

Dictionary<string, string> apiMapDict = 
    apiMap.ToDictionary(a => a.ApiName, a => a.ApiMessage); 

請注意,我已經改變了代碼存在的屬性名之間的差異您的示例(「名稱」,「消息」)和代碼示例(「apiName」,「apiMessage」)。

0

Attribute方法的參數是屬性名稱,而不是價值。將這些值替換爲屬性名稱。還可以使用Value屬性來獲取屬性的值。

即使這樣做雖然,作爲要素的屬性值將必須是唯一的 - 因爲你使用的是Dictionary<T,T>

Dictionary<string,string> apiMap = new Dictionary<string,string>();  
XDocument xdoc = XDocument.Load(path);  
apiMap = xdoc.Root.Elements() 
       .ToDictionary(a => a.Attribute("name").Value 
          , a => a.Attribute("message").Value); 
0

試試這個:

var xmlDocument = XDocument.Load(path); 
var values = xmlDocument 
      .Descendants("API") 
      .GroupBy(x => (string)x.Attribute("name")) 
      .ToDictionary(x => x.Key, 
          x => x.Select(p => (string)p.Attribute("message").ToList()); 

這會給你一個Dictionary<string, List<string>>,鍵是名稱,值是屬於Api名稱的消息。如果你只是想要字典,那麼更改代碼是這樣的:

var values = xmlDocument 
      .Descendants("API") 
      .GroupBy(x => (string)x.Attribute("name")) 
      .ToDictionary(x => x.Key, 
          x => (string)x.First().Attribute("message"));