Object reference not set to an instance of an object when trying to retrieve an element in an XML file

3

I have a bug tormenting me.

I'm basically saving the settings of all devices (RF Readers) in an XML file (Configs.xml). My goal is to retrieve the first element from all settings that has a "set" value (other than "") in the newLoot attribute. If the recovered element is different from null then I proceed with the code inside the IF, otherwise I'll throw an exception. However, the code below gives the following error when trying to retrieve the element (third line): Object reference not set to an instance of an object.

Can anyone tell me what I'm doing wrong? Thanks!

XElement xml = XElement.Load("Configs.xml");
XElement x = null;
x = xml.Elements().Where(p => !p.Attribute("novoLote").Value.Equals("")).FirstOrDefault();
if (x != null)
{
    ...
}
else
{
    throw new ReaderNaoConfiguradoParaFuncaoException("Nenhum Reader está configurado para essa função.");
}
    
asked by anonymous 20.10.2015 / 21:45

1 answer

2

This can be simplified to:

x = xml.Elements().FirstOrDefault(p => !p.Attribute("novoLote").Value.Equals(""));

Still, it is prone to errors. You can improve the sentence for:

x = xml.Elements().FirstOrDefault(p => p.Attribute("novoLote").Value != null && !p.Attribute("novoLote").Value.Equals(""))
    
20.10.2015 / 21:49