Ramya
Ramya

Reputation: 611

to avoid reading an rss node that is not present in the feed

I am reading an rss feed which has "credit" node in my item in most of the cases. While in some case it is not there..how do I avoid getting object not set exception? I am reading it this way using linq in c#

Credit = (string)item.Element(media + "credit").Value == null ? string.Empty : (string)item.Element(media + "credit").Value,

Upvotes: 0

Views: 48

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236278

You should check if element is not null before retrieving elements value:

var creditElement = item.Element(media + "credit");
Credit = (creditElement == null) ? string.Empty : (string)creditElement.Value;

But Linq is smart enough - it can explicitly cast element value to string and treat missing element as null. So you can just convert element to string, and with null coalescing operator assign default value:

Credit = (string)item.Element(media + "credit") ?? String.Empty;

Upvotes: 1

Related Questions