You can now embed XML directly within your Visual Basic code. This can make creating XML messages and executing queries against XML a simple task in VB. To support this feature, VB allows you to write straight XML when using the data types called System.Xml.Linq.XElement and System.Xml.Linq.XDocument. The former allows you to create a variable and assign it an XML element. The latter, XDocument, is used to assign a variable to a full XML document.

Writing XML within your code is a structured process and not just simple strings assigned to a parsing engine. In fact, the compiler uses LINQ to XML behind the scenes to make all of this work. Let’s look at a simple example. The following code creates a variable, emp, of type XElement. It then assigns the XML fragment to this variable.

Dim emp As XElement = <employee>
<firstName>Joe Smith</firstName>
<title>Sr. Developer</title>
<location state=”WA”>Redmond</location>

You can create a similar fragment as an XDocument. You simply add the XML document definition (<?xml version=”1.0”?>) to the header of the XML. In either scenario, you end up with XML that can be manipulated, passed as a message, queried, and more.

In most scenarios, however, you would not want to hard-code your XML messages in your code. You might define the XML structure there, but the data will come from other sources (variables, databases, and so on). Thankfully, Visual Basic also supports building the XML using expressions. To do so, you use an ASP-style syntax, as in <%= expression %>. In this case, you indicate to the compiler that you want to evaluate an expression and assign it to the XML. For XML messages with repeating data, you can even define a loop in your expressions. As an example, let’s look at building the previous XML using this syntax. Suppose you have an object e that represents an employee. In this case, you might write your XElement assignment as shown here:

Dim e As Employee = New Employee()
Dim emp As XElement = <employee>
<firstName><%= e.FirstName %></firstName>
<lastName><%= e.LastName %></lastName>
<title><%= e.Title %></title>
<company><%= e.Company %></company>
<location state=<%= e.Location.State %>>
<%= e.Location.City %>

VB allows you to write XML code. The two objects (XElement and XDocument) are still important additions to C# developers. However, C# developers will work with the properties and methods of these objects directly and not write and parse XML directly within a code editor.

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner