linq-to-xml - XDocument : Conditionally create new XElement

标签 linq-to-xml xelement

我的问题是关于有条件地创建 XElement,也就是说,如果满足某个条件,则创建 XElement,如果不满足,则跳过创建 XElement?此时,我可以创建空的 XElements,然后通过检查 IsEmpty 是否为真来删除所有空元素,但不知何故感觉不对......

我觉得,一个小例子可能是为了:

XDocument doc = new XDocument(new XDeclaration("1.0","utf-8","yes"),
new XElement("Books",
    new XElement("Book", new XElement("Title", "Essential LINQ"), new XElement("Author", "Charlie Calvert,Dinesh Kulkarni")),
    new XElement("Book", new XElement("Title", "C# in Depth"), new XElement("Author", "Jon Skeet")),
    new XElement("Book", new XElement("Title", "Some Title"), new XElement("Author", ""))
    ));

想象一下,“作者”元素是一个可选元素,如果我们不知道作者,我们就不会将该元素放在 XML 中——简单的,在我看来,丑陋的解决方案是创建元素, 作为一个空元素,然后将其删除。

任何人都知道如何制定一个优雅的解决方案,所以可以这样说:
condition_met ? new XElement("Author",variable_with_value) : do not create element

最好的问候,如果需要,请随时询问更多信息。

最佳答案

使用在构造中跳过空值的事实:

condition_met ? new XElement("Author", variable_with_value) : null

(LINQ to XML 充满了像这样的简洁小设计决策,使用起来很愉快。)

关于linq-to-xml - XDocument : Conditionally create new XElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3991063/

相关文章:

c# - 如何使用 LINQ 删除没有其子节点的 Xelement?

c# - linq 到 xml。读。并分配给 ViewData..noob

.net - 在 Linq 中将样式表引用添加到 XML 文档?

c# - 基于 XML 数据创建动态 linq-XML

c# - 如何获取 XML 或 XElement 变量中的特定元素计数

c# - Linq to XML 未获取所有节点

c# - close var XDocument.Load 方法/方式

c# - 使用 XElement 查询命名空间中的节点

c# - 从 XML 字符串生成 XElement 代码

c# - 选择一些特定的 xml 元素到匿名对象列表