Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for LINQ

July 2, 2009

XML Literals: Creating an XML File

Filed under: LINQ,VB.NET,XML @ 7:36 pm

One of my favorite features in VB 9 (Visual Studio 2008) is XML Literals. This example demonstrates how insanely easy it is to build an XML file using VB.

This code builds XML from a list of customers.

Dim customerXml As XElement = _
<customers>
   <%= From c In custList _
       Select <customer>
                 <LastName><%= c.LastName %></LastName>
                 <FirstName><%= c.FirstName %></FirstName>
              </customer> %>
</customers>

This code starts with the customers root node. It then builds a customer node for each customer found in the list.

This code then saves the XML to the defined file:

customerXml.Save("customers.xml")

NOTE: The definition of the Customer class and the list of customers (custList) used in the above example can be found here.

The resulting XML:

<customers>
  <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>

Enjoy!

P.S. In a later post here, I show how to read this XML file and reconstitute the list of customers.

« Previous Page

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