How to add XAttribute only if value is not null

I have following LINQ code to generate XML from a list of objects. When the AnalyteName is null or TestName is null, the following code will throw error. How can I add XAttribute only it the value is not null?

public static void StoreResult(List<LabPostResult> labPostResultList)
{
    var xml = new XElement("LabPostResult", labPostResultList.Select(x => new XElement("row",
                                     new XAttribute("PatientID", x.PatientID),
                                     new XAttribute("AnalyteName", x.AnalyteName),
                                     new XAttribute("TestName", x.Loinc)      
                                           )));
}

Class

public class LabPostResult
{
    public int PatientID { get; set; }
    public string AnalyteName { get; set; }
    public string TestName { get; set; }
}

2 answers

  • answered 2018-07-11 23:33 Selman Genç

    You can just pass in null if the property is null:

    var xml = new XElement("LabPostResult", labPostResultList.Select(x => new XElement("row",
                       new XAttribute("PatientID", x.PatientID),
                       x.AnalyteName != null ? new XAttribute("AnalyteName", x.AnalyteName) : null,
                       new XAttribute("TestName", x.Loinc)      
                                           )));
    

    This way the attribute won't be created for objects which don't have AnalyteName.

  • answered 2018-07-12 07:25 SMA

    You can write an extension method. It will much cleaner.

        public static XElement ToXElement(this string content, XName name)
        {
            return content == null ? null : new XElement(name, content);
        }
    

    And call it as below.

    public static void StoreResult(List<LabPostResult> labPostResultList)
        {
            var xml = new XElement("LabPostResult", 
                                    labPostResultList.Select(x => new XElement("row",
                                             new XAttribute("PatientID", x.PatientID),
                                             x.AnalyteName.ToXElement("AnalyteName"),
                                             x.Loinc.ToXElement("TestName")
                                                   )));
        }