Karthik
Karthik

Reputation: 2399

XDocument throws error when particular node is empty

Hi I have been using Xdoc to parse an xml .It works fine but throws error when a node is empty.How can we check for an empty node. EG: when the heard about tag has no value it throws an object reference not set to an instance of object error.

var data = from item in doc.Descendants("Order")
                                       select new
                                       {
                                           OrderID = item.Element("OrderID").Value,
                                           POnumber = item.Element("PurchaseNumber").Value,
                                           OrderDate = item.Element("DatePurchased").Value,
                                           source = item.Element("HearedAbout").Value
                                       }

i tried this but doesnot work

source = item.Element("HearedAbout").Value!=null?item.Element("HearedAbout").Value:"";

Upvotes: 0

Views: 495

Answers (3)

Derek.C
Derek.C

Reputation: 11

I think this is that:

source = Convert.ToString(item.Element("HearedAbout"))

Upvotes: 1

Rohit Agrawal
Rohit Agrawal

Reputation: 483

Check using the below menioned code

source = (string)item.Element("HearedAbout")

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500875

Yes, if item.Element("HearedAbout") returns null, then trying to use its Value property will indeed fail. The simplest approach is to cast it to string instead of using the Value property:

source = (string) item.Element("HearedAbout") ?? ""

The explicit conversion from XElement to string will return null when the element reference itself is null - and then the null coalescing operator takes care of the default value you want.

Given the rest of the names of your elements, I'd consider using the explicit conversions for those too:

select new
{
   OrderID = (int) item.Element("OrderID"),
   POnumber = (int) item.Element("PurchaseNumber"),
   OrderDate = (DateTime) item.Element("DatePurchased"),
   Source = (string) item.Element("HearedAbout") ?? ""
}

(The two int values might be some other type - look at your data to work it out.)

Also note that I've changed source to Source for consistency.

Upvotes: 3

Related Questions