Link to home
Start Free TrialLog in
Avatar of biksenbever
biksenbeverFlag for Netherlands

asked on

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!


ASKER CERTIFIED SOLUTION
Avatar of Gautham Janardhan
Gautham Janardhan

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of biksenbever

ASKER

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