Reputation: 137
Maybe I'm tired but I'm not seeing why this is only returning one result. There are three Program elements under Programs but I'm only getting Excel as the result. What am I missing and why?
XML:
<ServerRole>
<ServerType>Windows</ServerType>
<Programs>
<Program>Excel</Program>
<Program>Outlook</Program>
<Program>Word</Program>
</Programs>
</ServerRole>
Code snippet:
var proggies = xlServerRoles.Descendants("ServerRole")
.Where(prg => prg.Element("ServerType").Value == "Windows");
foreach (var prog in proggies.Descendants("Programs").Select(p => new
{
programName = p.Element("Program").Value
}))
{
alInstalledPrograms.Add(prog.programName.ToString());
}
Upvotes: 0
Views: 80
Reputation: 75316
It is because there is only one Programs
in your Xml, so the loop foreach
just loop only one time, for more corrective:
foreach (var prog in proggies.Descendants("Program").Select(p => new
{
programName = p.Value
}))
{
alInstalledPrograms.Add(prog.programName.ToString());
}
You can get descendants Program
directly in loop instead of Programs
. For shorten approach, you don't even need loop:
var alInstalledPrograms = xlServerRoles.Descendants("ServerRole")
.Where(prg => prg.Element("ServerType").Value == "Windows")
.Descendants("Program")
.Select(p => p.Value)
.ToList();
Upvotes: 2
Reputation: 126932
You use Element("Program")
where you expect plural Elements
, but your loop wouldn't quite get you there as it is. Try something more like
var installedPrograms = (from serverRole in xlServerRoles.Descendants("ServerRole")
where serverRole.Element("ServerType").Value == "Windows"
from program in serverRole.Element("Programs").Elements("Program")
select program.Value).ToList();
Upvotes: 1