XML Literals - (VB.NET only)

After I learned about lambda statements that they are supported only in C# 3.5 and not in VB.NET 9.0, I got curious and thought why not to find something that is available only for VB.NET and not for C#, and found this interesting thing which is called XML Literals. Using this nice features which is a part of LINQ to XML API, we can embed XML directly within Visual Basic 9.0 code.

To illustrate its power let's have a look at the below XML that we will produce using XML Literal.


<books>
<book>
<title>LINQ IN ACTION</title>
<author>FABRICE MARGUERIE</author>
<author>STEVE EICHERT</author>
<author>JIM WOOLEY</author>
<publisher>Manning</publisher>
</book>
</books>

now take a look at Listing 1.1 below, which shows the code for creating the XML using the XML literal syntax offered by VB9.

Listing 1.1

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim booksElement As XElement = <books>
<book>
<title>LINQ IN ACTION</title>
<author>FABRICE MARGUERIE</author>
<author>STEVE EICHERT</author>
<author>JIM WOOLEY</author>
<publisher>Manning</publisher>
</book>
</books>
End Sub

Note that in the above code we are using XElement which is a new class introduced in .NET 3.5 which represents an XML element. According to MSDN:
"XElement can be used to create elements; change the content of the element; add, change, or delete child elements; add attributes to an element; or serialize the contents of an element in text form"
The XML fragment in listing 1.1 above is static. When building real applications we might need to create XML using expressions stored in a set of local variables. XML Literal allows us to do so through expression holes which is expressed with the .

Listing 1.2

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim xml = LoadXML("LINQ IN ACTION", "Manning", "FABRICE MARGUERIE", "STEVE EICHERT", "JIM WOOLEY")

End Sub

Private Sub LoadXML(ByVal title As String, ByVal publisher As String, ByVal ParamArray authours() As String)

Dim booksElement As XElement = <books>
<book>
<title><%= title %></title>
<author><%= authours(0) %></author>
<author><%= authours(1) %></author>
<author><%= authours(2) %></author>
<publisher><%= publisher %></publisher>
</book>
</books>

End Sub

XML Literals allows us to embed XML directly within the code without having to learn the details of XML API. It's a great addition to VB9.0 and hope that it will get added to C# as well in future.



HTH,

0 comments:

Post a Comment