XML Literals: Handling Empty Elements
Thu, Mar 25 2010 10:31
In this prior post, I covered how to create an XML file using XML literals, a feature new in VB 9 (Visual Studio 2008). In this post, I'll look at handling empty elements.
If an element value is empty, you can create an empty element in the XML file using the techniques in the prior post mentioned above. But if your requirements are to remove the element if the value is empty, you have a little more code to write.
In VB: (Since C# does not support XML literals, no C# example is provided)
Dim customerXml As XElement = _
<%= From c In custList _
<LastName><%= c.LastName %></LastName>
<%= If(String.IsNullOrEmpty(c.FirstName), Nothing, _
<FirstName><%= c.FirstName %></FirstName>) %>
This code uses the new If ternary operator to assign the XElement <FirstName> or Nothing.
The resulting XML:
Use this technique any time you need to prevent generation of elements that have empty values.