A Quick Look at XML Literals

XML literals are new to Visual Studio 2008 and Visual Basic. Simply put they enable the incorporation of XML directly into application code. Essentially this allows a quick way to create XML objects. At their core XML literals represent a LINQ to XML object and follow syntax similar to XML 1.0. At run time XML literals are turned into their equivalent calls to the LINQ to XML object. This makes it easier to create XML elements and documents programmatically because you code has the same structure as the final XML.  One of the clear advantages of using XML literals is that they can span multiple lines without need a line continuation. This makes code look similar to an XML file. At run time the compiler treats the line continuation characters as part of the XML literal. For example, using the XElement, which represents the fundamental XML construct we can create the following code.

Dim CProduct As XElement = _

           <Product>

               <name>Stereo</name>

               <department id="612">

                   <deptname>Engineering</deptname>

                   <cost>50</cost>

               </department>

           </Product>

        TextBox1.Text = CProduct.ToString

At runtime this produces the following

You can also embed a Visual Basic expression in an XML literal. At run time your application creates a LINQ to XML object for each literal, incorporate the values of the embedded expressions. This lets you specify dynamic content inside an XML literal. For example, the following code takes an XML document literal and builds an XML document.

  Dim CProduct As XElement = _

    <Product>

        <ProductName>Stereo</ProductName>

    </Product>

        Dim doc As XDocument = _

        <?xml version="1.0"?>

        <Products>

            <%= From i In Enumerable.Range(1, 5) _

                Select New XElement(CProduct) %>

        </Products>

        TextBox1.Text = doc.ToString

At run time this produces the following