24

I'm using LINQ together with XDocument to read a XML File. This is the code:

XDocument xml = XDocument.Load(filename);

var q = from b in xml.Descendants("product")
        select new
        {
            name = b.Element("name").Value,
            price = b.Element("price").Value,                    
            extra = b.Element("extra1").Value,
            deeplink = b.Element("deepLink").Value                   
        };

Now the problem is, the extra1 field is not always present. There are items in the XML file without that node. If that happens it's crashing with a NullReferenceException.

Is there any possibility to include a "check if null" so I can prevent it from crashing?

4 Answers 4

43

Use (string) instead of .Value:

var q = from b in xml.Descendants("product")
        select new
        {
            name = (string)b.Element("name"),
            price = (double?)b.Element("price"),                    
            extra = (string)b.Element("extra1"),
            deeplink = (string)b.Element("deepLink")                   
        };

This also works with other datatypes, including many nullable types in case the element is not always present.

Sign up to request clarification or add additional context in comments.

Comments

9

You can use "null coalescing" operator:

var q = from b in xml.Descendants("product")
        select new
        {
            name = (string)b.Element("name") ?? "Default Name",
            price = (double?)b.Element("price") ?? 0.0,                    
            extra = (string)b.Element("extra1") ?? String.Empty,
            deeplink = (string)b.Element("deepLink") ?? String.Empty                   
        };

This way, you will have full control about default value used when there's no element.

1 Comment

price needs to be double? for that line to make sense.
2

Use the following example for checking existence of any element before using that element.

if( b.Elements("extra1").Any() )
{
   extra = b.Element("extra1").Value;
}

Comments

1

Here is sample example to read XML file using XDocument.

  XDocument objBooksXML = XDocument.Load(Server.MapPath("books.xml"));
    var objBooks = from book in
                   objBooksXML.Descendants("Book")
                   select new { 
                                Title = book.Element("Title").Value, 
                                Pages = book.Element("Pages").Value 
                              };

    Response.Write(String.Format("Total {0} books.", objBooks.Count()));
    gvBooks.DataSource = objBooks;
    gvBooks.DataBind();

1 Comment

The problem with this code is that if "Book" doesn't contain a "Title" or "Pages" element you'll throw a null exception when trying to get .Value from either of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.