c# - 仅当值不为空时如何添加 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; }
}
解决方案
您可以编写扩展方法。它会干净得多。
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")
)));
}
推荐阅读
- r - R中的moran.test
- java - 我在哪里可以找到实现 org.osgi.service.log.LoggerFactory 服务的包?
- apache-spark - “spark.yarn.executor.memoryOverhead”和“spark.memory.offHeap.size”之间的区别
- javascript - 根据数据属性范围显示 li 元素
- python - Turtle 代码不起作用,显示 py-lint no member 错误
- python - 随机时间延迟非整数
- python - 在 def 范围内使用 pandas 函数是否有问题
- php - Laravel 无法连接到 XAMPP MySQL 数据库(Windows)
- python - 将 tf.Dataset 提供给 fit() 时出错:KeyError: 'embedding_input'
- html - 父显示:flex 不适用于子 div?