Monday, December 17, 2007

XML in Visual Basic.NET 9.0 and Visual Studio 2008

One of the new features available in the VB .NET 9.0 compiler is it's deep integration with XML.  The below is a perfectly legal syntax to send to the Visual Basic compiler.

Dim customers = <customers>
        <customer id="1">
            <firstname>Jim</firstname>
            <lastname>Fiorato</lastname>
        </customer>
        <customer id="2">
            <firstname>Mister</firstname>
            <lastname>Pickles</lastname>
        </customer>
    </customers>
 
    For Each customer In customers.<customer>
 
    Console.WriteLine(customer.@id & " - " & customer.<firstname>.Value & "  " & customer.<lastname>.Value)
 
Next
Console.ReadLine()

Yep, that's right.  No quotes around the XML.  And there's Intellisense too:

image

Here's what it looks like when decomposed by Reflector:

XElement VB$t_ref$S0 = new XElement(XName.Get("customers", ""));
XElement VB$t_ref$S1 = new XElement(XName.Get("customer", ""));
VB$t_ref$S1.Add(new XAttribute(XName.Get("id", ""), "1"));
XElement VB$t_ref$S2 = new XElement(XName.Get("firstname", ""));
VB$t_ref$S2.Add("Jim");
VB$t_ref$S1.Add(VB$t_ref$S2);
VB$t_ref$S2 = new XElement(XName.Get("lastname", ""));
VB$t_ref$S2.Add("Fiorato");
VB$t_ref$S1.Add(VB$t_ref$S2);
VB$t_ref$S0.Add(VB$t_ref$S1);
VB$t_ref$S1 = new XElement(XName.Get("customer", ""));
VB$t_ref$S1.Add(new XAttribute(XName.Get("id", ""), "2"));
VB$t_ref$S2 = new XElement(XName.Get("firstname", ""));
VB$t_ref$S2.Add("Mister");
VB$t_ref$S1.Add(VB$t_ref$S2);
VB$t_ref$S2 = new XElement(XName.Get("lastname", ""));
VB$t_ref$S2.Add("Pickles");
VB$t_ref$S1.Add(VB$t_ref$S2);
VB$t_ref$S0.Add(VB$t_ref$S1);
XElement customers = VB$t_ref$S0;
foreach (XElement customer in customers.Elements(XName.Get("customer", "")))
{
    Console.WriteLine(InternalXmlHelper.get_AttributeValue(customer, XName.Get("id", "")) + " - " + InternalXmlHelper.get_Value(customer.Elements(XName.Get("firstname", ""))) + "  " + InternalXmlHelper.get_Value(customer.Elements(XName.Get("lastname", ""))));
}
Console.ReadLine();

This is such a great paradigm shift.  As developers, we're so used to pushing strings that represent rich languages like SQL and XML into our code, which totally removes the compile checks from these languages.  LINQ and now VB.NET XML are closing this gap, and making the development experience far more productive.

0 comments: