VB.Net inline XML loop

July 20, 2010 at 9:43 PMRampidByter

Coming from a C# background I was a little jealous of VB literals (still hate VB.) Recently I was flung into the VB.Net world on a new project, and my only consolation was finally being able to work with VB literals first hand. The first thing I needed to do was iterate a collection of objects to custom build an XML message. I did a little Google, and Bing action to no real results on looping a collection within XML literals. Eventually I found the solution as XML literals do not directly support loops as we know it. Fortunately that is where LINQ steps up to the plate:

 1: Dim xml = <Processes>
 2:  <%= From process in Processes 
 3:  Select <Process><%= process.Name %></Process>
 4:  %>
 5:  </Processes>

In this example I’ve created an XElement variable called “xml” that contains the literal XML. Using a LINQ query within the “Processes” element the select query will iterate through the items in the processes collection object. Each item will output a process element that will be included within the processes element.

Posted in: .Net | Programming

Tags: