简体   繁体   中英

C# Linq XML Query where multiple elements of same name from a parent node based on a child node value

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();

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM