Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

March 25, 2010

XML Literals: Handling Empty Elements

Filed under: VB.NET,XML @ 12:31 pm

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!

1 Comment

  1.   Art Colman — March 29, 2010 @ 9:39 am    Reply

    Very nice! Thanks.

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs