Reputation: 2977
I am a newbie and trying to retrieve all the values of file node based on below xml.
<Changes>
<Change id="Rest">
<Name>Restructure</Name>
<TIDE>
<Files>
<File>REGION</File>
</Files>
</TIDE>
<Click>
<Files>
<File>DISTRICT</File>
</Files>
</Click>
</Change>
<Change id="st">
<Name>New ST</Name>
<TIDE>
<Files>
<File>REGION</File>
</Files>
</TIDE>
<Click>
<Files>
<File>DISTRICT</File>
</Files>
</Click>
</Change>
</Changes>
The code I am using is giving me an error "Sequence contains no elements". I have tried to build this code by searching couple of examples on this forum. Can some one help me, much appreciated.
var items = (from i in xmldoc.Root.Elements("Change")
where (string)i.Element("Name").Value == listBox1.SelectedValue.ToString()
select i).First().Elements("File").ToList();
Upvotes: 0
Views: 1078
Reputation: 89325
This LINQ query returns Change
nodes:
(from i in xmldoc.Root.Elements("Change")
where (string)i.Element("Name").Value == listBox1.SelectedValue.ToString()
select i)
... and Change
nodes don't have direct child node File
. You can use Descendants()
instead of Elements()
for this case.
var items = (from i in xmldoc.Root.Descendants("Change")
where i.Element("Name").Value == listBox1.SelectedValue.ToString()
select i).First().Descendants("File").ToList();
Upvotes: 2
Reputation: 4259
This error you are getting:
"Sequence contains no elements"
Is beeing throwed by the First() Method call. First() Expects at least one result to be listed, and your filter in Where clause is removing all the results (probably not getting Names correctly from the listbox).
I tested on my machine, replacing the listBox1.SelectedValue.ToString() for "Restructure" and the error doesn't happens anymore.
Even though the exception was not throwed, the result was not as you expected, the items list was empty. To address this other issue you must follow har07 response, and everything will work just fine.
Upvotes: 1