Search code examples
c#xmlxelement

Setting properties for object only when present in database


I have an object that is supposed to describe some customer with these values:

{
    public class CustomerDescription
    {
        public string FirstName { get; set; } = "";
        public string LastName { get; set; } = "";
        public string StreetName { get; set; } = "";
        public string HouseNumber { get; set; } = "";
        public string PostalPlace { get; set; } = "";
        public string PostCode { get; set; } = "";
        public string CountryCode { get; set; } = "";
        public string EMail { get; set; } = "";
        public string PhoneNumber { get; set; } = "";
    }
}

These values are retrieved from a database of customers and will be used to create an XML file which will be sent via SOAP to another database. However, not all these values are always present. For example one customer may not have the country code in the database. In this case I would like to not include this value at all in the XML file I am sending. Here is an example of how I create the XML elements:

new XElement("address",
           new XElement("address1", CustomerDescription.StreetName + " " + cabCustomerDescription.HouseNumber),
           new XElement("postalCode", cUstomerDescription.PostCode),
           new XElement("city", customerDescription.PostalPlace),
           new XElement("countryCode", customerDescription.CountryCode))
)

This is done for all the properties in CustomerDescription. My question is, how can I do this so that if a value is not present in the database, then this value is not included in the XML file? I would not like it to be empty, like <countryCode></countryCode>, but rather not present at all.


Solution

  • You just need to use ternary operator if value is null from database dont include in x element.

    Ex:Explicitely i did StreetName null an dcheck if null then dont add in xml file.

    CustomerDescription t = new CustomerDescription();
     t.StreetName = null;
                var abc = new XElement("address", t.StreetName != null ? new XElement("address1", t.StreetName + " " + t.HouseNumber) : null,
                new XElement("postalCode", t.PostCode),
                new XElement("city", t.PostalPlace),
                new XElement("countryCode", t.CountryCode));