NullReferenceException 在尝试检索配置属性时出现未处理错误

本文关键字:未处理 错误 属性 配置 检索 NullReferenceException | 更新日期: 2023-09-27 18:36:01

    public string GetLogName(string config)
    {
        XDocument xDoc = XDocument.Load(config);
        XElement[] elements = xDoc.Descendants("listeners").Descendants("add").ToArray();
        foreach (var element in elements)
        {
            if (element.Attribute("fileName").Value != null)
            {
                string filename = element.Attribute("fileName").Value;
                int location = filename.IndexOf("%");
                Console.WriteLine("string to return: " + filename.Substring(0, location));
                return filename.Substring(0, location);
            }
        }
    }

我正在尝试从元素数组中的每个元素中检索"文件名"属性,但在某些情况下,"文件名"属性不存在并失败并出现以下错误:NullReferenceException 未处理。对象引用未设置为对象的实例。

在我的例子中,有两个"添加"节点没有

"文件名"属性,但第三个添加节点具有它。

如何跳过没有"fileName"属性的条目,或者是否可以推荐更好的方法来检索此属性?

NullReferenceException 在尝试检索配置属性时出现未处理错误

一种方法是在处理列表之前过滤掉它:

XElement[] elements = xDoc.Descendants("listeners")
                          .Descendants("add")
                          .Where (d => d.Attribute("filename") != null )
                          .ToArray();

---恕我直言,这就是我使用 linq 和正则表达式重写该方法的方式---

var elements =
XDocument.Load(config);
         .Descendants("listeners")
         .Descendants("add")
         .Where (node => node.Attribute("filename") != null )
         .ToList();

return elements.Any() ? elements.Select (node => node.Attribute("filename").Value )
                                .Select (attrValue => Regex.Match(attrValue, "([^%]+)").Groups[1].Value)
                                .First ()
                      : string.Empty;

您应该能够通过更改此行来执行此操作:

if (element.Attribute("fileName").Value != null)

自:

if (element.Attribute("fileName") != null)

将你的if语句改为:

if (element.Attribute("fileName") != null)