首页 > 解决方案 > 仅当值不为空时如何添加 XAttribute

问题描述

我有以下 LINQ 代码从对象列表生成 XML。当 AnalyteName 为 null 或 TestName 为 null 时,以下代码将抛出错误。如何仅在值不为空的情况下添加 XAttribute?

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

班级

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

标签: c#linq

解决方案


您可以编写扩展方法。它会干净得多。

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

并将其称为如下。

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

推荐阅读