XML Literals: Handling Empty Elements

Posted Thu, Mar 25 2010 10:31 by Deborah Kurata

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 = _
    <customers>
      <%= From c In custList _
        Select <customer>
                <LastName><%= c.LastName %></LastName>
                <%= If(String.IsNullOrEmpty(c.FirstName), Nothing, _
                  <FirstName><%= c.FirstName %></FirstName>) %>
                </customer> %>
    </customers>

This code uses the new If ternary operator to assign the XElement <FirstName> or Nothing.

The resulting XML:

<customers>
  <customer>
    <LastName>Jones</LastName>
  </customer>
  <customer>
    <LastName>Baggins</LastName>
    <FirstName>Billbo</FirstName>
  </customer>
  <customer>
    <LastName>Baggins</LastName>
    <FirstName>Frodo</FirstName>
  </customer>
  <customer>
    <LastName>Kurata</LastName>
    <FirstName>Deborah</FirstName>
  </customer>
</customers>

Use this technique any time you need to prevent generation of elements that have empty values.

Enjoy!

Filed under: , ,

Comments

# Interesting Finds: March 26, 2010

Friday, March 26, 2010 6:31 AM by Jason Haley

Interesting Finds: March 26, 2010

# re: XML Literals: Handling Empty Elements

Monday, March 29, 2010 9:39 AM by Art Colman

Very nice! Thanks.

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: