Tarek Saied
Tarek Saied

Reputation: 6616

How to check if a xml file contains specific element using linq to xml

In my XML file i want to check if i have and device element in my xml file

i try this code but give me Null Reference Exception if it not found a device element

public bool HaveAnyDevice()
{
    XDocument doc = XDocument.Load(path);
    return !doc.Element("Settings").Elements("Device").Any();
}

Upvotes: 0

Views: 2384

Answers (2)

Habib
Habib

Reputation: 223247

If you are getting a NRE then your doc.Element("Settings") is null. You may check it before checking the next element.

return doc.Element("Settings") != null && 
       doc.Element("Settings").Elements("Device").Any();

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Your code should work. I think you don't have element Settings in your xml. So, just verify if it exists before trying to get it's elements:

 public bool HaveAnyDevice()
 {
     XDocument doc = XDocument.Load(path);
     var settings = doc.Element("Settings");
     return (settings != null) && settings.Elements("Device").Any();
 }

Upvotes: 1

Related Questions