为什么抛出NullReferenceException?

时间:2011-03-27 19:11:54

标签: c# .net 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); 
}  

为什么抛出

  

System.NullReferenceException未被用户代码

处理

在这一行

if (xml.Element(parent).Element(node).Value != null)

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

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

感谢您的帮助。

6 个答案:

答案 0 :(得分: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;
    }
}

更新

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

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

答案 1 :(得分:1)

几乎可以肯定,因为它返回null:

xml.Element(parent)

答案 2 :(得分:1)

您需要检查是否:

Element(node) != null

致电之前.Value。如果Element(node)== null,则对.Value的调用将抛出空引用异常。

答案 3 :(得分:1)

尝试将if语句更改为:

if (xml.Element(parent).Element(node) != null)

如果父元素中的节点为null,则无法访问空对象的成员。

答案 4 :(得分:1)

至少:

private void alterNodeValue(string xmlFile, string parent, string node, string newVal)
{
    XDocument xml = XDocument.Load(this.dir + xmlFile);
    XElement parent = xml.Element(parent).Element(node);
    if (parent  != null)
    {
        parent.Value = newVal;
    }
    else
    {
        xml.Element(parent).Add(new XElement(node, newVal)); 
    }    
    xml.Save(dir + xmlFile); 
}  

更好:

private void alterNodeValue(string xmlFile, string parent, string node, string newVal)
{
    string path = System.IO.Path.Combine(dir, xmlFile);
    XDocument xml = XDocument.Load(path );
    XElement parent = xml.Element(parent).Element(node);
    if (parent != null)
    {
        XElement node = parent.Element(parent);
        if (node != null)
        {
            node.Value = newVal;
        }
        else
        {
            // no node
        }
    }
    else
    {
        // no parent
    }    
    xml.Save(path); 
}  

答案 5 :(得分:0)

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