Reputation: 3243
I am trying to create a generic method that will read an xml and return the node name and attribute value as a dictionary item .
I have been playing around with the syntax but can't seem to quite get it right. What am I missing here?
Currently I have:
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);
Upvotes: 1
Views: 40
Reputation: 1461
You should wrap your LINQ query by brackets:
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"]);
}
Upvotes: 2