XML Literals: Creating an XML File
Posted
Thu, Jul 2 2009 17:36
by
Deborah Kurata
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.