This is my idea for the code (can the Linq query populate the dictionary object directly?).
XElement doc = XElement.Load(data.xml);
string Element = "KeyNode";
string SearchString = "Dominion";
Dictionary<string, string> QueryData = new Dictionary<string, string>();
var query = from child in doc.Descendants(Element)
where SearchString == child.Value
select pn.Parent.Elements();
foreach(XElement x in query)
{
QueryData.Add(x.Name.ToString(),x.Value);
}
I would do this to create the dictionary:
However, that’s only safe if you know your XML doesn’t have any duplicate names. If it might have duplicate names, you may want to get a distinct list in your query, or else investigate
ToLookup()as an alternative toToDictionary().Also, your code is storing the tag name as the dictionary key. If that’s what you need, then great. But if you actually need the value of a tag attribute or something like that, then you’ll need to change your code.
Update
I think I see what the problem is. You never actually stated what your difficulty in iterating the results is, but I think this might be it:
The
Elements()method returns anIEnumerable<XElement>. That means that the type of yourqueryvariable is actuallyIEnumerable<IEnumerable<XElement>>. If you want to flatten that down to a single list of all the elements, here’s how: