---
title: "Add XElement only if value exists"  
description: "Add XElement only if value exists"  
author: "Pravesh Singh"  
published: 2013-09-04  
updated: 2013-09-04  
canonical: https://www.mindstick.com/forum/1448/add-xelement-only-if-value-exists  
category: "c#"  
tags: ["c#"]  
reading_time: 1 minute  

---

# Add XElement only if value exists

I'm creating an XDocument using [Linq](https://www.mindstick.com/articles/12007/language-integrated-query-linq-queries)-To-[XML](https://www.mindstick.com/blog/203/working-with-xml-data-in-sql-server), like this:

[Order](https://www.mindstick.com/articles/12276/how-timely-order-deliveries-can-improve-customer-experience) order = GetOrder();

XDocument doc = new XDocument(

new XElement("purchaseOrder",

new XElement("[Name](https://yourviews.mindstick.com/view/87450/how-to-generate-a-brand-name-using-linkedin-comprehensive-guide)", order.Name),

new XElement("Address", order.Address),

new XElement("Shipper", order.Shipper)

)

);

So sometimes an order will not have a Shipper, it will be null. In that case, I don't want to include the Shipper element at all.

How can I do that [inline](https://www.mindstick.com/interview/1012/describe-the-difference-between-inline-and-code-behind) in my [code](https://yourviews.mindstick.com/view/85458/alan-turing-the-mastermind-behind-cracking-the-enigma-code-during-world-war-ii) when creating the doc?

## Replies

### Reply by Sumit Kesarwani

Hi Pravesh,\

Just check if the Shipper value is null. If it isn't, then add your element, otherwise just set it to null. A null value in the constructor translates to nothing added in its place.

```
Order order = GetOrder();XDocument doc = new XDocument(  new XElement("purchaseOrder",        new XElement("Name",order.Name),        new XElement("Address", order.Address),        order.Shipper != null ? new XElement("Shipper", order.Shipper) : null    ));
```


---

Original Source: https://www.mindstick.com/forum/1448/add-xelement-only-if-value-exists

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
