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 %>

           </string>.Value

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”

DoIt(<param>

         <customer>

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

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

         </customer>

     </param>)

 

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

        Console.WriteLine(c.ToString())

    Next

 

 

End Sub

Enjoy,
-B