Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

September 1, 2010

XML Literals: Creating XML

Filed under: VB.NET,XML @ 11:05 pm

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>
                     <Customer>
                         <LastName><%= lastName %></LastName>
                         <FirstName><%= firstName %></FirstName>
                     </Customer>
                 </Customers>
    Return xmlDoc.ToString
End Function

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:

In VB:

Dim xmlResult = BuildXML("Baggins", "Bilbo")

Here is the resulting XML:

<Customers>
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Bilbo</FirstName>
  </Customer>
</Customers>

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.

Enjoy!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs