The power of XLINQ in Visual Basic 2008

By Mohammad Mahdi Ramezanpour at August 14, 2008 01:19
Filed Under: LINQ, XML

Using LINQ to XML (XLINQ) will help you to access your XML data very easier, like never before. But I don't know why, using XLINQ in Visual Basic is more interesting than C# for me.

In this post I want to show you how easy can be for VB to generate an XML file than C#.

Assume that we want to generate an XML file like following:

<?xml version="1.0" encoding="utf-8" ?>
<configs>
    <config name="Mohammad Mahdi Ramezanpour"></config>
</configs>

 

In order to generate such a thing in C#, you will need to write something like this:

XDocument xdoc = new XDocument();
XElement xroot = new XElement("configs");
XElement xitem = new XElement("config", 
                 new XAttribute("Name", "Mohammad Mahdi Ramezanpour"));
xroot.Add(xitem);
xdoc.Add(xroot);
xdoc.Save("C:\\sample.xml");

As you can see, I just created a new XDocument and then add some XElements to it. All things are very routine and then I saved the data into an XML file "C:\sample.xml".

Now, lets check such the code above in Visual Basic:

Dim xdoc As New XDocument
Dim xroot As XElement = <configs></configs>
Dim xitem As XElement = <config name="Mohammad Mahdi Ramezanpour"></config>
xroot.Add(xitem)
xdoc.Add(xroot)
xdoc.Save("C:\sample.xml")

in the code above I created an XML file exactly like our previous exmple and the result will be equal.

Lets take a look at this code snippet; In Visual Basic when you declare a variable as XElement, you can write your XML content exactly like the syntax you're using in an XML file. It means that you can use XML tags (<configs></configs>) straight in your code.

As I said in my previous posts, I like VB more than C# and I thing VB is much powerful than C# at least in this part :).

Comments are closed

Currently Reading

Quote of the day

Send Persian SMS