简体   繁体   中英

NullReferenceException was unhandled error when trying to retrieve config attributes

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

I am trying to retrieve the "fileName" attribute from each element in the elements array, but there are some cases when the "fileName" attribute does not exist and fails with the following error: NullReferenceException was unhandled. Object reference not set to an instance of an object.

In my case there are two "add" nodes that do not have a "fileName" attribute, but the third add node has it.

How can I skip over entries that do not have a "fileName" attribute, or can you recommend a better way to retrieve this attribute?

You should be able to do this simply by changing this line:

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

To:

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

将您的if语句更改为此:

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

One way is to filter out the list before you process it:

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

--- IMHO this is how I would rewrite the method, using linq and regex ---

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM