Gero
Gero

Reputation: 13553

How to handle NullReferenceException when Linq to xml parsing attribute

I have a simple xml.

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

Now i have n different XElement items in FildsInData.

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

With that fail attribute i get nullReferenceException, because it is not there. Sometimes it is, sometimes it is not. How do i handle that gracefully?

I tryed using value.SingleOrDefault(); but i get another exception because it is IEnumerable of Char.

Upvotes: 0

Views: 1171

Answers (2)

Botz3000
Botz3000

Reputation: 39620

Just to add another way to do this, you could also abuse Extension Methods for null checking:

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

And then use it like that:

string notExistingAttribute = item.Attribute("fail").ValueOrDefault();

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

You simply need to check for null:

String notExistingAttribute = "";

var attribute =  item.Attribute("fail");
if(attribute != null)
    notExistingAttribute = attribute.Value;

Upvotes: 0

Related Questions