Home > Linq > Use LINQ to XML to create XML document from Database

Use LINQ to XML to create XML document from Database


Hi

try this example to Use LINQ to XML to create XML document from database :-

1) Open VS 2008

2) Create new website

3) Add the following code in code behind :-

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True"))
            {
                conn.Open();
                SqlCommand comm = new SqlCommand("select CategoryID, CategoryName, Description from Categories", conn);
                IDataReader reader = comm.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(reader);
                var xmlDoc = new XDocument(
                    new XElement("rootElement",
                        new XElement("categories",
                            from cat in dt.AsEnumerable()
                            select new XElement("category",
                                       new XAttribute("CategoryID", cat["CategoryID"]),
                                       new XAttribute("CategoryName", cat["CategoryName"]),
                                       new XAttribute("Description", cat["Description"])
                                )
                       )
                    )
                );
                Response.Clear();
                Response.ContentType = "text/xml";
                xmlDoc.Save(Response.Output, SaveOptions.None);
                Response.End();
                reader.Close();
                comm.Dispose();
            }
        }
    }
}

Hope this helps

Good Luck

Advertisements
Categories: Linq Tags:
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: