2

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

我有这几行代码:

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% 的时间它工作得很好。

我的问题 :

formatID在尝试读取节点之前如何检查节点是否存在Value

4

6 回答 6

3

你可以使用DefaultIfEmpty()吗?

例如

var sFormatId = xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"]
                                  .Value.DefaultIfEmpty("not found").Single();

或者正如其他人所建议的那样,检查该属性是否不为空:

if (xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"] != null)
于 2013-07-17T16:13:04.703 回答
2

如果节点不存在,则返回 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。

于 2013-07-17T16:09:43.783 回答
2

你也可以这样做:

            if (xDoc.ChildNodes[0].HasChildNodes)
            {   
                foreach (XmlNode item in xDoc.ChildNodes[0].ChildNodes)
                {
                    string sFormatId;
                    if(item.Attributes["formatID"] != null)
                       sFormatId = item.Attributes["formatID"].Value;

                    // Do some stuff
                }     
            }
于 2013-07-17T16:30:20.540 回答
1

你可以像这样检查

 if(null != xDoc.ChildNodes[0].ChildNode[i].Attributes["formatID"])
于 2013-07-17T16:12:37.167 回答
1

我认为更清洁的方法是:

var xDoc = new XmlDocument();
xDoc.LoadXml(xelementVar.ToString());

foreach(XmlNode formatId in xDoc.SelectNodes("/*/*/@formatID"))
{
    string formatIdVal = formatId.Value; // guaranteed to be non-null
    // do stuff with formatIdVal
}
于 2013-07-17T17:12:46.073 回答
1

在大多数情况下,我们遇到问题是因为 XPath 不存在,它返回 null 并且我们的代码由于 InnerText 而中断。

您只能检查 XPath 是否存在,不存在时返回 null。

if(XMLDoc.SelectSingleNode("XPath") <> null)
  ErrorCode = XMLDoc.SelectSingleNode("XPath").InnerText
于 2016-03-28T06:55:34.300 回答