Question regarding nested LINQ to XML queries:
code:
List<string> GetNames(string fooName)
{
string fileName = "foo.xml";
XElement myFile = XElement.Load(fileName);
IEnumerable<XElement> bars =
from response in myFile.Elements("foo")
where response.Attribute("fooName").Value.Equals(fooName)
from subResponse in response.Descendants()
select subResponse;
List<string> sNames = new List<string>();
foreach (XElement el in bars)
{
XAttribute NameAttr = el.Attribute("Name");
sNames.Add(NameAttr.Value);
}
return sNames;
}
xml:
<topElem>
<foo fooname="a">
<bar Name= "bb"/>
<bar Name= "cc"/>
<bar Name= "dd"/>
</foo>
</topElem>
question:
What I am trying to do is build a list that has “bb”, “cc”, and “dd” in it, when I called the above function with an argument of “a”. While the above code works, I think if I was more fluent in LINQ I would be able to produce my List directly in the LINQ code and not have to rely on the foreach loop to iterate over the IEnumerable. I’ve looked at a number of examples on this site and others trying to find this exact case, but haven’t had much luck. I’ve seen some examples that use lambda expressions or that do other operations on the “select” statement, but I haven’t had any luck getting code which compiles out of that. Maybe adding a 3rd from statement, something like
from subSubResponse in subResponse.Attribute("Name")
select subResponse.Value
But that gives an error:
An expression of type ‘System.Xml.Linq.XAttribute’ is not allowed in a subsequent from clause in a query expression with source type ‘System.Collections.Generic.IEnumerable’. Type inference failed in the call to ‘SelectMany’.
You can only use
fromon an expression that returns a collection..Attribute("Name")does not return a collection, so that line doesn’t make sense.You may want
or just