XML Literals Tips/Tricks

A couple quick tips here when using XML literals in your Visual Basic programs.

#1: I’ve started using XML literals everywhere I had been using multiline strings and text merging (as I explained in this post). For instance, I started using them in my ToString methods of my classes:

Public Overrides Function ToString() As String

    Return <string>

ID       : <%= Me.ID %>

Name     : <%= Me.LastName %>, <%= Me.FirstName %>

Address  : <%= Me.Address %>

         : <%= Me.City %>, <%= Me.State %> <%= Me.Zip %>


End Function

#2: It’s also sometimes handy to pass an XElement as a parameter if you need dynamic parameters, or were using your own custom parameter objects previously:

Dim id = 1

Dim name = “Beth”



             <id><%= id %></id>

             <name><%= name %></name>




Private Sub DoIt(ByVal param As XElement)


    Dim customers = From customer In param…<customer> _

            Select New Customer With _

            {.ID = customer.<id>.Value, _

             .FirstName = customer.<name>.Value}


    For Each c In customers





End Sub