开发者

XDocument: Conditionally create new XElement

开发者 https://www.devze.com 2023-01-21 01:06 出处:网络
My question is regarding conditionally creation of XElements, that is, if some condition is met, create the XElement, if not, skip creating the XElement? At this point of time, I could create empty XE

My question is regarding conditionally creation of XElements, that is, if some condition is met, create the XElement, if not, skip creating the XElement? At this point of time, I could create empty XElements, and then remove all empty elements, by checking, if IsEmpty is true, but that somehow does not feel right...

I feel, that a small example might be in order:

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

Imagine, that the "Author"-element is an optional element, 开发者_StackOverflow中文版and if we do not know the author, we simply do not put that element in the XML - the simple, and in my opinion, ugly solution, is to create the element, as an empty element, and remove it afterwards.

Anyone know how to make an elegant solution, so to say something like this:

condition_met ? new XElement("Author",variable_with_value) : do not create element

Best regards and feel free to ask for further information, if needed.


Use the fact that nulls are skipped in construction:

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

(LINQ to XML is full of neat little design decisions like this that make it a pleasure to work with.)

0

精彩评论

暂无评论...
验证码 换一张
取 消