我不知道为什么我在这方面遇到了这么多麻烦,但我希望有人能给我指出正确的方向。
我有这几行代码:
var xDoc = new XmlDocument();
xDoc.LoadXml(xelementVar.ToString());
if (xDoc.ChildNodes[0].HasChildNodes)
{
for (int i = 0; i < xDoc.ChildNodes[0].ChildNodes.Count; i++)
{
var sFormatId = xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"].Value;
// Do some stuff
}
// Do some more stuff
}
问题是我得到的 xDoc
并不总是有 formatID
节点,所以我最终得到一个空引用异常,虽然 99%它工作得很好的时候。
我的问题:
在尝试从中读取 Value
之前,如何检查 formatID
节点是否存在?
最佳答案
如果节点不存在,则返回null。
if (xDoc.ChildNodes[0].ChildNode[i].Attributes["formatID"] != null)
sFormatId = xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"].Value;
你可以用捷径来做
var sFormatId = xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"] != null ? xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"].Value : "formatID not exist";
格式是这样的
var variable = condition ? A : B;
这基本上是说,如果条件为真,则变量 = A,否则,变量 = B。
关于c# - XML - 检查特定节点是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17704805/