Home > Blockchain >  XElement.Element doesn't return a null value
XElement.Element doesn't return a null value

Time:04-01

When I run the program and I set a wrong value for _moduleParent the exception appears and says 'Object reference not set to an instance of an object.'

I want to return a null string. How can I deal with this exception?

string sioModuleName = "";
string sioModuleDescription = String.Empty;
try
{
    XDocument xDoc = new XDocument();
    xDoc = XDocument.Load(_xmlPath);
    //Root
    var sioModule = xDoc.Element(_moduleName);
    if(sioModule != null)
    {
        sioModuleName = sioModule.Element(_moduleParent).Value;//here is the problem
        sioModuleDescription = sioModule.Element("SIO-DEFINITION").Value;
    }
    else
    {
        MessageBox.Show("Incorrect Module Name");
        return;
    }
}

CodePudding user response:

XContainer.Element(XName) returns an XElement if an element with the specified name exists, otherwise it will return null. Your exception occurs because you are reading the Value property of a null reference. So you need to handle that. There are two options:

Use the built-in explicit conversions:

sioModuleName = (string)sioModule.Element(_moduleParent);

Use the null-conditional operator:

sioModuleName = sioModule.Element(_moduleParent)?.Value;
  • Related