A day with .Net

My day to day experince in .net

Datatable to XML using LINQ

Posted by vivekcek on May 29, 2012

If you want to create an XML like this below


<Root name="root" xmlns="http://www.google.com/namespace">
<Child id="1" name="vivek" />
<Child id="2" name="chanthu" />
</Root>

From the table

 

The below code will be useful


DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");

DataRow dr = dt.NewRow();
dr["id"] = "1";
dr["name"] = "vivek";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["id"] = "2";
dr["name"] = "chanthu";
dt.Rows.Add(dr);

XNamespace x1 = "http://www.google.com/namespace";

XElement xt = new XElement(x1 + "Root", new XAttribute("name", "root"),
from p in dt.AsEnumerable()
select new XElement(x1 + "Child", new XAttribute("id", p["id"]),
new XAttribute("name", p["name"])));

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s