in

vbCity Blogs

New (temp) place for vbCity Blogs

Larry's Blog

XML, take 4

I just got a note from Visual Basic MVP Steele Price, who pointed out a fourth way of writing XML.  Unlike the three in my last post, this method will not work in C#.

As I should have mentioned, VB allows you to put XML directly in your code, which is great if you don't need to do a lot of dynamic modification to the XML.  Now with LINQ, you can also insert variables, using a syntax resembling Classic ASP.

Since Steele was nice enough to send me a good example, I'll just post his.

Sub xml5(ByVal peoplepairs As IList(Of KeyValuePair(Of Integer, String)))
     'convert the List to XML
     Try
            Dim thelist = _
            <People>
                <%= From p In peoplepairs _
                    Select _
                    <Person id=<%= p.Key.ToString %>><%= p.Value %></Person> %>
            </People>

            ' Start document and write header
            Dim xd As New XDocument(New XDeclaration("1.0", "UTF-8", "yes"), thelist)

            Try
                'Save the file
                xd.Save("MyXML.xml")

            Catch ex2 As Exception
                'do something here if the save fails
            End Try

        Catch ex1 As Exception
            'do something here if the conversion fails
        End Try
End Sub

There's always more ways to skin the cat.  Steele's website is http://blog.steeleprice.net/ .  Thanks! 

Only published comments... Oct 28 2009, 11:49 AM by LarryBlake

About LarryBlake

Larry has been involved with Microsoft development tools since 1992, with Visual Basic 1.0.  He currently holds a Microsoft MVP in Visual Basic. Larry is available for contract coding in VB, C# and ASP, and for Project Management. See: http://mysite.verizon.net/lmmblake . 

Copyright 1998-2009 vbCity.com LLC
Powered by Community Server (Non-Commercial Edition), by Telligent Systems