为什么抛出NullReferenceException?

PiZ*_*zL3 0 .net c# exception-handling linq-to-xml nullreferenceexception

private void alterNodeValue(string xmlFile, string parent, string node, string newVal)
{
    XDocument xml = XDocument.Load(this.dir + xmlFile);

    if (xml.Element(parent).Element(node).Value != null)
    {
        xml.Element(parent).Element(node).Value = newVal;
    }
    else
    {
        xml.Element(parent).Add(new XElement(node, newVal)); 
    }

    xml.Save(dir + xmlFile); 
}  
Run Code Online (Sandbox Code Playgroud)

为什么这会抛出

System.NullReferenceException未被用户代码处理

在这条线上

if (xml.Element(parent).Element(node).Value != null)
Run Code Online (Sandbox Code Playgroud)

我猜这是因为XML节点不存在,但这就是我们!= null要检查的内容.我该如何解决这个问题?

我已经尝试了几件事,他们在非空检查期间的某些时刻抛出相同的异常.

谢谢你的帮助.

Ode*_*ded 7

无论xml.Element(parent)或者Element(node)你正试图从返回值的访问xml.Element(parent)null.

像这样的重组将使您能够看到它是哪一个:

var myElement = xml.Element(parent);
if (xmyElement != null)
{
    var myNode = myElement.Element(node);
    if(myNode != null)
    {
      myNode.Value = newVal;
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

从您的评论看起来你想要这样做:

if (xml.Element(parent).Element(node) != null)  // <--- No .Value
{
    xml.Element(parent).Element(node).Value = newVal;
}
else
{
    xml.Element(parent).Add(new XElement(node, newVal)); 
}
Run Code Online (Sandbox Code Playgroud)