c# - XML - 检查特定节点是否存在

标签 c# xml

我不知道为什么我在这方面遇到了这么多麻烦,但我希望有人能给我指出正确的方向。

我有这几行代码:

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/

相关文章:

java - 自定义 Java XMLBuilder 与基于标准类的对比

java - 如何使 XmlPullParser 返回顶级元素的列表?

c# - WPF TabItem HeaderTemplate

c# - 添加到聚合根时未保存子实体

c# - 如何在 c# 中将字符串从 utf8 转换(音译)为 ASCII(单字节)?

android - 解析 XML 时出错 : unbound prefix for mapbox

xml - 如何从 Oracle 表中检索特定的 XML 节点?

c# - 是否可以同时验证自签名证书和真实证书?

c# - Azure函数: Blob identifiers must be in the format 'container/blob'

Java XML 解析错误 : Content is not allowed in prolog