XElement.Element 不是 return 空值

XElement.Element doesn't return a null value

当我 运行 程序并且我为 _moduleParent 设置了错误的值时,出现异常 并说 'Object reference not set to an instance of an object.'

我想 return 一个空字符串。我该如何处理这个异常?

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

XContainer.Element(XName) return 如果具有指定名称的元素存在,则为 XElement,否则它将 return null。发生异常是因为您正在读取空引用的 Value 属性。所以你需要处理它。有两种选择:

使用 built-in 显式转换:

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

使用null-conditional运算符:

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