我的问题是关于有条件地创建 XElement,也就是说,如果满足某些条件,则创建 XElement,如果没有,跳过创建 XElement?此时,我可以创建空 XElement,然后删除所有空元素,方法是检查 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
最好的问候,如果需要,请随时询问更多信息。