HANDLE NULL EXCEPTION IN LINQ TO XML QUERY

Ankita Pandey

Total Post:183

Points:1285
Posted by  Ankita Pandey
C# 
C#
 1413  View(s)
Ratings:
Rate this:

var qXML = (from nm in xelement.Descendants("EmployeeFinance")

            where nm.Element("Status").Value.Contains(status) && int.Parse(nm.Element("Empersonal_Id").Value) == ele.EmpId

            select nm).SingleOrDefault();

Above is my sample code. Now there are instances where ele.EmpId will be present in the xml and instance where it will not be. How do i handle the null exception that is thrown when ele.EmpId is not found.

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Handle null exception in linq to xml query

    Hi Ankita, 

    This checks both if the element is null and the element contains a non empty/null string value, and will short circuit if it fails either of those checks, before it tries to parse.

    var qXML = (from nm in xelement.Descendants("EmployeeFinance")

                where nm.Element("Status").Value.Contains(status) &&

                ((nm.Element("Empersonal_Id") != null) &&

                 !string.IsNullOrEmpty(nm.Element("Empersonal_Id").Value) &&

                 int.Parse(nm.Element("Empersonal_Id").Value) == ele.EmpId)

                select nm).SingleOrDefault();

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!