XML Literals: Creating XML
Wed, Sep 1 2010 21:05
This post covers the technique for creating XML using XML literals.
This post continues the series on using XML literals which starts here. Since XML literals are a VB.NET feature only (new in VB 9/VS 2008), this post only includes VB.NET code.
The scenario is that we need to build an XML document, maybe to send to a Web service or to save data to a local file system. In this case, the task is to write customer information, including the customer's name.
Here is the code in VB.NET:
Private Function BuildXML(ByVal lastName As String,
ByVal firstName As String) As String
Dim xmlDoc = <Customers>
<LastName><%= lastName %></LastName>
<FirstName><%= firstName %></FirstName>
This function passes parameters containing the data for the XML string. In a real application, this could be many customer fields including address and phone information. The function then returns the XML as a string.
The code within the function uses XML literals to build the XML string. Notice how the code mimics the layout of the resulting XML. Using XML literals in this manner can dramatically simplify creation of XML with less code and fewer errors because you can see how the resulting XML will look.
The <%= expression %> syntax defines an embedded expression. An embedded expression enables you to define an expression within the XML that is evaluated at runtime. So the above code replaces the contents of the specified tags with the parameter values.
This code can be called using syntax like this:
Dim xmlResult = BuildXML("Baggins", "Bilbo")
Here is the resulting XML:
Use this technique any time you need to build XML data with VB.Net.
For an example of saving the XML to a file and of building an XML string from a list of objects, see this prior post.