0

我有一个简单的 xml。

        var FieldsInData = from fields in xdoc.Descendants("DataRecord")
                           select fields;

现在我在 FildsInData 中有 n 个不同的 XElement 项目。

        foreach (var item in FieldsInData)
        {
            //working
            String id = item.Attribute("id").Value;
            //now i get a nullReferenceException because that XElement item has no Attribute called **fail**
            String notExistingAttribute = item.Attribute("fail").Value;
        }

使用该失败属性,我得到 nullReferenceException,因为它不存在。有时是,有时不是。我该如何优雅地处理它?

我尝试使用 value.SingleOrDefault(); 但我得到另一个例外,因为它是 Char 的 IEnumerable。

4

2 回答 2

2

只是为了添加另一种方法来执行此操作,您还可以滥用扩展方法进行空检查:

public static class XmlExtensions 
{
    public static string ValueOrDefault(this XAttribute attribute) 
    {
        return attribute == null ? null : attribute.Value;
    }
}

然后像这样使用它:

string notExistingAttribute = item.Attribute("fail").ValueOrDefault();
于 2012-08-17T13:22:38.140 回答
0

您只需要检查null

String notExistingAttribute = "";

var attribute =  item.Attribute("fail");
if(attribute != null)
    notExistingAttribute = attribute.Value;
于 2012-08-17T13:17:41.930 回答