Monday, September 24, 2007

XML Literals in VB 9.0

  I usually live in the C# world, have been since 1.0 of the .Net framework. Back then I was interested in VB.Net until the "Don't change VB" crowd started clamoring, at that point I knew that for at least the time being VB.Net would be crippled so I moved on to C#. I've looked at it from time to time since 1.0, but none of it's features has really stood out from the crowd, until now.

  I've spent a great deal of time looking at an experimenting with the .Net 3.5 changes around LINQ and C# and VB.Net are equally matched, with the exception of XML Literals, which is a VB only feature. So what is an XML Literal? Quite simply it's the ability to embed XML directly into your code. Ok, your saying, "I can do this today, so what's the big deal?", the big deal is the XML is a first class object, not a string! In addition to embedding the XML directly in your code, you can also embed expressions in the form of "<%= [exp] %>", which allows you to populate the XML programmatically.

Here's a VB.Net code snippet that populates an XML Literal using an expression to assign the element values:

Public Function PopulateXml(ByVal boundary As Boolean _
                                            , ByVal endPoint As Boolean _
                                            , ByVal vertex As Boolean) As XElement
       Dim snapSettings As XElement = _
       <SnappingOptions>
           <Boundary><%= boundary.ToString() %></Boundary>
           <Endpoint><%= endPoint.ToString() %></Endpoint>
           <Vertex><%= vertex.ToString() %></Vertex>
       </SnappingOptions>

       Return snapSettings
   End Function

 

The code example above returns a LINQ XElement object, the nodes are populated using the expression defined inside the XML.In the end this allows you to produce XML output that matches the original document format and it's embedded right in the code.

 My hats off to the VB team for this little gem, I hope the C# team pays attention and adds it to C# 4.0.

No comments: