ADD XELEMENT ONLY IF VALUE EXISTS

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
C# 
C#
 1999  View(s)
Ratings:
Rate this:

I'm creating an XDocument using Linq-To-XML, like this:

Order order = GetOrder();

XDocument doc = new XDocument(

    new XElement("purchaseOrder",

        new XElement("Name", 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 in my code when creating the doc?

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: Add XElement only if value exists

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

      Modified On Mar-31-2018 12:43:15 AM

Answer

NEWSLETTER

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