Home > DeveloperSection > Forums > Handle null exception in linq to xml query
Ankita Pandey
Ankita Pandey

Total Post:183

Points:1285
Posted on    August-14-2014 5:11 AM

 C# C# 
Ratings:


 1 Reply(s)
 996  View(s)
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.



Pravesh Singh

Total Post:411

Points:2881
Posted on    August-14-2014 6:53 AM

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();


Don't want to miss updates? Please click the below button!

Follow MindStick