---
title: "Handle null exception in linq to xml query"  
description: "Handle null exception in linq to xml query"  
author: "Anonymous User"  
published: 2014-08-14  
updated: 2014-08-14  
canonical: https://www.mindstick.com/forum/2039/handle-null-exception-in-linq-to-xml-query  
category: "c#"  
tags: ["c#"]  
reading_time: 1 minute  

---

# Handle null exception in linq to xml query

var qXML = (from nm in xelement.Descendants("EmployeeFinance")

where nm.Element("[Status](https://www.mindstick.com/articles/157184/check-lic-policy-status-online-by-policy-number)").Value.Contains(status) && int.Parse(nm.Element("Empersonal_Id").Value) == ele.EmpId

[select](https://www.mindstick.com/forum/160534/orderby-then-select-vs-select-then-orderby-performance) nm).SingleOrDefault();

Above is my sample code. [Now](https://yourviews.mindstick.com/view/81402/it-s-liberals-vs-progressives-in-us-politics-now) there are [instances](https://answers.mindstick.com/qa/92508/how-can-you-hide-the-sql-server-instances) where ele.EmpId will be [present](https://answers.mindstick.com/qa/96635/explain-about-the-various-features-present-in-ms-access) in the [xml](https://www.mindstick.com/blog/203/working-with-xml-data-in-sql-server) and [instance](https://www.mindstick.com/forum/155658/testing-connection-to-cloud-sql-instance-with-a-mysql-client-from-vm-instance) where it will not be. How do i [handle](https://www.mindstick.com/articles/311004/suede-skillet-handle-cover) the [null](https://www.mindstick.com/forum/33922/how-to-use-null-coalescing-operator-in-c-sharp) [exception](https://www.mindstick.com/articles/1824/objective-c-exception-handling) that is thrown when ele.EmpId is not found.

## Replies

### Reply by Pravesh Singh

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();
```


---

Original Source: https://www.mindstick.com/forum/2039/handle-null-exception-in-linq-to-xml-query

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
