[英]Why does this throw a 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
所要檢查的內容。 我該如何解決?
我已經嘗試了幾件事,並且它們在不為null的檢查過程中的某些時候都拋出了相同的異常。
謝謝你的幫助。
您嘗試從xml.Element(parent)
的返回值訪問的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));
}
幾乎可以肯定,因為它返回null:
xml.Element(parent)
您需要檢查是否:
Element(node) != null
在調用.Value之前。 如果Element(node)== null,則對.Value的調用將引發null引用異常。
擔
嘗試將您的if語句更改為此:
if (xml.Element(parent).Element(node) != null)
如果父元素中的節點為null,則無法訪問null對象的成員。
至少:
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);
}
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.