Freigeben über


How To: Seemlessly Export Data From Database to XML using LINQ

 

While exploring a number of neat features available in the Visual C# Orcas Express Edition, you will see the following:

There is no namespace like DLinq, or XLinq anymore, they are replace with more meaningful
System.Data.Linq and
System.Xml.Linq

However, the latter appears by default in a console application, System.Data.Linq will be added to the references once the O/R mapper a.k.a .dbml file is added. In the express Edition, you can connect to a .mdf, .mdb, or a .sdf(Sql Server Compact Edition) databases.

After instantiating the DataContext class, you will be able to explore its rich features supported with Intellisence.

Apart from that the XML.Linq namespace has got some neat and intuitive features. My favorite is:
System.Xml.Linq.XElement xlinq = new XElement(XName name, object content);

As you would expect from it, any object returning values compatible to IEnumerable is taken care of by the constructor... all by itself.

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Xml.Linq;
  
 namespace ConsoleApplication1
 {
     class Program
     {
         static void Main(string[] args)
         {
             NorthwindDataContext north = new NorthwindDataContext();
             //sample query, not related to this demo!!
             var products = from p in north.Products
                            where p.ProductID > 10 && p.ProductID < 200
                            select new{
                                       p.ProductName,
                                       p.UnitPrice
                                   };
             //the actual thing!!!
             System.Xml.Linq.XElement xlinq = new XElement("Products",
                                              from p in north.Products
                                              where p.ProductName.StartsWith("S")
                                              select new XElement("Product", new XAttribute("UnitPrice", p.UnitPrice),
                                                     new XAttribute("QuantityPerUnit", p.QuantityPerUnit), 
                                                         new XElement("ProductName", p.ProductName),
                                                     new XElement("SupplierName", p.Supplier.CompanyName)
                                                         )
                                              );
             xlinq.Save("NewXML.xml");
             Console.Write(xlinq);            
             Console.Read();
         }
     }    
 }

The output in the (command window) looks like the following:

Check out this space, lots more coming up...

Microsoft ROCKS!!!

Comments