Google PlusFacebook iconTwitter icon+44 113 260 4010 contact@branded3.com

Creating XML with Visual Basic

I’m of the opinion that you should use the right tool for the job. In the case of making simple XML files from data in another source, the XML literals feature in Visual Basic works very well and tends to be my first choice.

Check out how simple creating XML documents can be:

Module Music

    Sub Main()

        Using data = New MusicDataContext()

            Dim xml = <Artists>
                          <%= From artist In data.Artists
                              Select <Artist>
                                         <Name><%= artist.Name %></Name>
                                         <Songs>
                                             <%= From song In artist.Songs
                                                 Select <Song><%= song.Title %></Song>
                                             %>
                                         </Songs>
                                     </Artist> %>
                      </Artists>

            File.WriteAllText("Music.xml", xml.ToString())

        End Using

    End Sub

End Module

Running this code just outputs a simple XML file which looks like this:

<Artists>
  <Artist>
    <Name>Justin Bieber</Name>
    <Songs>
      <Song>One Less Lonely Girl</Song>
      <Song>Baby</Song>
    </Songs>
  </Artist>
  <Artist>
    <Name>Rebecca Black</Name>
    <Songs>
      <Song>Friday</Song>
    </Songs>
  </Artist>
</Artists>

As you can see, the output and the code look very similar, and while you could create something like this in C# by using the equivalent XElement objects, it will never look as simple to me. Maybe one day we’ll get these pretty XML literals in C# too?

BY Julian Kay AT 3:36pm ON Friday, 15 April 2011

Our Senior Application Developer, Jules has been immersed in the software development industry for 12 years; revolutionising Branded3’s development process’s for almost three of those years. As well as being our server and mobile development expert; Jules surrounds himself with all things Microsoft and Windows. This isn’t just his job, this is his passion. Follow @juliankay on Twitter

Comments

Comments are closed.