Wednesday, December 15, 2010

Using XML literals in VB.Net with Linq

The XML literal support is the second thing I have seen special in Visual Basic which is really amazing.The first feature was the support for multiple indexer properties .XML literals helps us to create XElement by just writing plain XML in the VB.net code.This simple definition will not help anybody to learn what is XMl literals and their importance in dealing with xml.So let’s consider an example of XML serialization.
I have a class say Employee with 2 properties Name as string and ID as integer.The requirement is to get a XML representation of the employee collection.

Public Class Employee
Public Property Name As String
Public Property Id As Integer
End Class


If I pass a list of employee class I need out put like.


<Employees>
<Employee Name="Joy" Id="Joy" />
<Employee Name="George" Id="George" />
</Employees>


Here is the traditional code.


Private Function GetXMLTraditional(ByVal employees As List(Of Employee)) As String
Dim xEle As New XElement("Employees")
For Each emp In employees
Dim xEleEmp As New XElement("Employee")
xEleEmp.SetAttributeValue("Name", emp.Name)
xEleEmp.SetAttributeValue("Id", emp.Id)
xEle.Add(xEleEmp)
Next
Return xEle.ToString()
End Function


Look at the code which uses XML literals.


Private Function GetXMLUsingXMLLiterals(ByVal employees As List(Of Employee)) As String
Return <Employees>
<%= From emp In employees _
Select <Employee Name=<%= emp.Name %> Id=<%= emp.Name %>/>
%>
</Employees>.ToString
End Function



I don’t think I need to explain anything further about the advantages.If you are a ASP.Net developer you might already understood the use of “<%= %>”

No comments: