views:

15

answers:

1

Hi all,

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, 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.

+1  A: 

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

Jon Skeet
Excellent Jon, thank you :)
Claus Pontoppidan