As easy as LINQ has made data access, it has made working
with XML even easier. With LINQ, you don't need to create complex classes in
order to serialize them. Instead, XML is a native type in Visual Basic, so XML
elements can be stated explicitly, intermixed with output commands to insert
the correct values.
To create our XML document, we'll still need to instantiate
an XML document, then add our elements, starting with the outermost (root)
element. Change Sub Main() to read as below:
Listing 5
Sub Main()
Dim _db As New ProductsDataContext
Dim _products = From p In _db.vProductModelCatalogDescriptions Select p
Dim _xml As New Xml.Linq.XDocument
Dim _xp As New XElement("Products")
_xml.Add(_xp)
_xml.Save("ProductCatalog.xml")
End Sub
Press F5 to run this code - it should execute just fine.
You can see the sample output in your bin/Debug folder (if necessary, remember
to click the Show All Files button in the Solution Explorer). We should have
an XML declaration, and an empty Products element.
To add the details for each product, we need to loop through
our collection of products and insert the proper values into each element.
We'll use another of the new features in VB9, and explicitly state XML elements
in our code. Change Sub Main() to read as below. As you type the XML
elements, notice that Visual Studio adds the closing element automatically.
Feel free to add more elements if you want to. You can refer to the DBML file
we created above for a list of available fields. If you've ever used inline
ASP.NET code on a web form, the shorthand <%= %> notation will be
familiar to you. Essentially, this shorthand means to insert (or print) the
value contained inside the brackets.
Listing 6
Sub Main()
Dim _db As New ProductsDataContext
Dim _products = From p In _db.vProductModelCatalogDescriptions Select p
Dim _xml As New Xml.Linq.XDocument
Dim _xp As New XElement("Products")
For Each _p In _products
_xp.Add(<Product>
<ProductId><%= _p.ProductModelID %></ProductId>
<Name><%= _p.Name %></Name>
<Wheel><%= _p.Wheel %></Wheel>
<BikeFrame><%= _p.BikeFrame %></BikeFrame>
</Product>)
Next
_xml.Add(_xp)
_xml.Save("ProductCatalog.xml")
End Sub
Once you've made these changes, press F5, and check the
output file after execution completes. You should see all the products listed,
with all the elements you specified. If your example is not working properly,
double check your syntax and make sure you entered it as show above. The
syntax inside the for each loop will seem strange at first, but keep in mind
that XML is a native type in VB 9, so XML elements can be directly specified in
our code.