Question

    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?

Était-ce utile?

La solution

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;

Autres conseils

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

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

To:

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

change your if statement to this :

if (element.Attribute("fileName") != null)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top