2016-05-16 108 views
1

我想創建一個通用的方法,它將讀取一個xml並返回節點名稱和屬性值作爲字典項目。如何從xml創建字典項目?

我一直在玩弄語法,但似乎無法完全正確。 我在這裏錯過了什麼?

目前我有:

XElement doc = XElement.Load(dataStream); 
var item = from el in doc.Descendants() 
      where el.Attribute(attributeName) != null 
      select new 
      { 
       Name = el.Name.LocalName, 
       Value = el.Attribute(attributeName).Value 
      }.ToDictionary(o => o.Name, o => o.Value); 

回答

2

你應該用方括號包住LINQ查詢:

public void Test() 
{ 
    const string attributeName = "name"; 
    XElement doc = XElement.Parse(@"<xml><elem id=""1"" /><anotherElem name=""test"" /></xml>"); 
    var items = (from el in doc.Descendants() 
     where el.Attribute(attributeName) != null 
     select new 
     { 
      Name = el.Name.LocalName, 
      Value = el.Attribute(attributeName).Value 
     }).ToDictionary(o => o.Name, o => o.Value); 

    Assert.AreEqual(1, items.Count); 
    Assert.AreEqual(true, items.ContainsKey("anotherElem")); 
    Assert.AreEqual("test", items["anotherElem"]); 
} 
+0

我正要張貼我的答案。我沒有意識到我忘了包裝查詢。 – PrivateJoker