Reputation: 6616
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
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
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