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

C# XML-检查是否存在特定节点,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 sForma

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

我有以下几行代码:

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
}
var xDoc=new XmlDocument();
LoadXml(xelementVar.ToString());
if(xDoc.ChildNodes[0].HasChildNodes)
{
对于(int i=0;i
问题是我得到的
xDoc
并不总是有
formatID
节点,因此我最终得到了一个空引用异常,尽管99%的时间它工作得非常好

我的问题:


在尝试从中读取
值之前,如何检查
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。

您可以这样检查

 if(null != xDoc.ChildNodes[0].ChildNode[i].Attributes["formatID"])
你能用一下吗

例如

或者按照其他人的建议,检查属性是否不为null:

if (xDoc.ChildNodes[0].ChildNodes[i].Attributes["formatID"] != null)
您也可以这样做:

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

我认为一个更干净的方法是:

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
}

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

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

if(XMLDoc.SelectSingleNode("XPath") <> null)
  ErrorCode = XMLDoc.SelectSingleNode("XPath").InnerText
if(XMLDoc.SelectSingleNode(“XPath”)null)
ErrorCode=XMLDoc.SelectSingleNode(“XPath”).InnerText

+1对于
DefaultIfEmpty
建议,我已经完全忘记了这一点。在尝试读取值之前,我使用了
null
检查。你是第一个回答的人,所以功劳归你——谢谢!感谢您提出的重新分解建议,我已将其转换为使用
foreach
而不是
for
if(XMLDoc.SelectSingleNode("XPath") <> null)
  ErrorCode = XMLDoc.SelectSingleNode("XPath").InnerText