代码之家  ›  专栏  ›  技术社区  ›  LCJ

仅当值不为空时如何添加xattribute

  •  1
  • LCJ  · 技术社区  · 7 年前

    我使用下面的LINQ代码从对象列表中生成XML。当analyteName为空或testname为空时,以下代码将引发错误。如何仅在值不为空时添加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; }
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Selman Genç    7 年前

    如果属性为空,则可以传入空值:

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

    这样就不会为没有属性的对象创建属性 AnalyteName .

        2
  •  0
  •   Ayaz    7 年前

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

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