---
title: "Reading XML using XDocument &amp; Linq"  
description: "Reading XML using XDocument &amp; Linq"  
author: "Royce Roy"  
published: 2014-08-27  
updated: 2014-08-27  
canonical: https://www.mindstick.com/forum/2176/reading-xml-using-xdocument-amp-linq  
category: "asp.net"  
tags: ["asp.net"]  
reading_time: 1 minute  

---

# Reading XML using XDocument &amp; Linq

I'm using [LINQ](https://www.mindstick.com/articles/12007/language-integrated-query-linq-queries) [together](https://yourviews.mindstick.com/view/80819/live-in-relationship-protecting-the-right-to-live-together) with XDocument to read a [XML File](https://www.mindstick.com/forum/360/how-to-read-xml-file-in-php). This is the [code](https://yourviews.mindstick.com/view/85458/alan-turing-the-mastermind-behind-cracking-the-enigma-code-during-world-war-ii):

```
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](https://yourviews.mindstick.com/view/81399/tackling-the-problem-of-unemployment-during-corona-pandemic) is, the extra1 [field](https://www.mindstick.com/forum/160867/does-mindstick-provide-training-for-field-marketing) is not always present. There are [items](https://www.mindstick.com/forum/33812/getting-number-of-items-selected-in-uicollectionview-in-ios) 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](https://www.mindstick.com/forum/12878/how-to-check-if-an-asp-dot-net-file-upload-control-has-a-file-in-jquery) [null](https://www.mindstick.com/forum/33922/how-to-use-null-coalescing-operator-in-c-sharp)" so I can prevent it from crashing?

## Replies

### Reply by Sumit Kesarwani

Hi Royce,

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")                           };
```


---

Original Source: https://www.mindstick.com/forum/2176/reading-xml-using-xdocument-amp-linq

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
