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

为什么这掷为什么会抛出NullReferenceException?

System.NullReferenceException是由用户代码

未处理的在这条线

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

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

我试过几件事情,它们都在非空检查期间的某个时刻抛出相同的异常。

感谢您的任何帮助。

回答

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

存在父节点没有。我试图抓住'Element(node)== null'并通过'else'语句添加它。 – PiZzL3 2011-03-27 19:15:47

+1

@ PiZzL3 - 如果你知道它不存在,你为什么在_non existent_节点上做'.Value'? – Oded 2011-03-27 19:17:58

+0

我仍然在学习如何正确使用'XDocument'。我不知道所有的细节。 – PiZzL3 2011-03-27 19:19:54

1

这几乎肯定是因为这返回null:

xml.Element(parent) 
1

您需要检查:

Element(node) != null 

在打电话前.value的。如果Element(node)== null,那么对.Value的调用将抛出一个空引用异常。

1

尝试改变if语句来这是你的:

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

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

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