Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

September 1, 2010

XML Literals: Creating XML with a Namespace

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

This post covers the technique for creating XML that includes an XML namespace (xmlns) attribute.

From Wikipedia:

XML namespaces are used for providing uniquely named elements and attributes in an XML document.

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), these posts will only include VB.NET code.

The scenario is the same as the prior post, except that the XML contains an XML namespace attribute. Here is the text from the  prior post:

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 xmlns="
http://customer/2010/info">
                     <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, including the definition of the namespace (xmlns) attribute. 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 xmlns="http://customer/2010/info">
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Bilbo</FirstName>
  </Customer>
</Customers>

Use this technique any time you need to build XML with a namespace in VB.Net.

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