ausgeorge
ausgeorge

Reputation: 1015

LINQ to XML - check for null?

I've been using LINQ for about 2 days, so please bear with me.

Here's my current code;

_resultList = (
from
    item in _documentRoot.Descendants("MyItems")
select
    new MyClass
    {
        XMLID = item.Attribute("id").Value
    }).ToList<MyClass>();

Most of the elements have an 'id' attribute, and they get added to the list successfully. Some, however, don't have an 'id'. For these, I'd like 'id' to just be an empty string.

How do I check to see if the attribute exists before trying to access it? thanks

Upvotes: 1

Views: 2044

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

You don't need to store attribute in additional variable. If attribute is not there, then casting attribute to string will return null. With power of null-coalescing operator you can provide default value - empty string:

from item in _documentRoot.Descendants("MyItems")
select new MyClass {
        XMLID = (string)item.Attribute("id") ?? ""
    }

Upvotes: 8

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could store it in a variable and based on whether this variable is null define the value of the XMLID property:

from item in _documentRoot.Descendants("MyItems")
let idAttr = item.Attribute("id")
select new MyClass
{
    XMLID = idAttr != null ? idAttr.Value : string.Empty
}).ToList<MyClass>();

Upvotes: 5

Related Questions