Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument: Conditionally create new XElement

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.

like image 928
Claus Pontoppidan Avatar asked Oct 21 '10 19:10

Claus Pontoppidan


1 Answers

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

like image 166
Jon Skeet Avatar answered Oct 25 '22 15:10

Jon Skeet