How to query nested XML Elements with Linq

I am just trying to convert my XML node-select statements to Linq. Now I am stuck because I am having problems with the nested structure of my XML document.

I my program I need to query an export from a commercial program named 'Endnote' (which is used for registering scientific articles).

The structure is (partly)
<records>
   <record>
      <rec-number>152</rec-number>
      <ref-type name="Journal Article">17</ref-type>
      <contributors>
        <authors>
          <author>
            <style face="normal" font="default" size="100%">Thuiller, W.</style>
          </author>
        </authors>
      </contributors>
      <titles>
        <title>
          <style face="normal" font="default" size="100%">Patterns and uncertainties of species&apos; range shifts under clmate change</style>
        </title>
        <secondary-title>
          <style face="normal" font="default" size="100%">Global Change Biology</style>
        </secondary-title>
      </titles>
      ... rest of nodes ...
   </record>
  ... rest of records ...
</records>

I tried successfully selecting records havind a specific recordnumber with:
 
            XElement test = XElement.Load("EndnoteExport.xml");

           var records = from record in test.Descendants("record")
                          where record.Element("rec-number").Value.Equals(someValue)
                          select record;

But how can I select all records from a specific author for example?

Thanks for any help!


biksenbeverAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Gautham JanardhanConnect With a Mentor Commented:
var records = from record in test.Descendants("record")
                              where record.Element("Authors").Element("author").Value.Equals(somevalue)
                              select record;
0
 
biksenbeverAuthor Commented:
Thank you very much, that looks really easy!

It first tried it and it did not work because I got an 'object not set to an instance' error.
Later on I saw that for some records the elements are optional.
So I added to the where clause:
where (record.Element("someElementName") != null) && 

ecetera

0
All Courses

From novice to tech pro — start learning today.