0

i am processing xml file by using following code,but how to check null reference exception which i used to get

var main = System.Xml.Linq.XDocument.Load("1.xml");

string localcellid = main.Descendants()
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "eNodeBCell_eNodeB"))
    .Descendants("parameter")
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "LocalCellId"))
    .Attribute("value").Value;

string eNodeBId = main.Descendants()
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "eNodeB_eNodeB"))
    .Descendants("parameter")
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "eNodeBId"))
    .Attribute("value").Value;
peter
  • 8,158
  • 21
  • 66
  • 119

1 Answers1

0

As Nikosi said, every FirstOrDefault has the potential to return null and you need to take this into account.

You can check it ahead (I added only 1 check as example):

var eNodeBCell_eNodeB = main.Descendants()
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "eNodeBCell_eNodeB"));

if (eNodeBCell_eNodeB != null)
{
    string localcellid = eNodeBCell_eNodeB
        .Descendants("parameter")
        .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "LocalCellId"))
        .Attribute("value").Value;
}

Or you can use null-conditional operator (?.):

string eNodeBId = main.Descendants()
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "eNodeB_eNodeB"))
    ?.Descendants("parameter")
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "eNodeBId"))
    ?.Attribute("value").Value;

Anyway you will need to check for null values of those values later.

JleruOHeP
  • 10,106
  • 3
  • 45
  • 71