简体   繁体   中英

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

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

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

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