In this article I will explain with an example, how to export data from Database to XML file in ASP.Net MVC.
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
You will need to import the following namespaces.
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply View is returned.
Action method for handling POST operation
Inside this Action method, the DataSet is populated with records from the database table named Customers.
Then, an instance of MemoryStream class is created.
Now, the DataSet is converted to an XML string using the WriteXml method and copied to the MemoryStream class object.
Finally, the MemoryStream class object is converted to Byte Array and downloaded as XML file using the File function.
public class HomeController : Controller
// GET: Home
public ActionResult Index()
public ActionResult Export()
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customers", con))
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
using (DataSet ds = new DataSet("Customers"))
ds.Tables.TableName = "Customer";
using (MemoryStream stream = new MemoryStream())
return File(stream.ToArray(), "application/xml", "Customers.xml");
Inside the View there as HTML Form, which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Export.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Also, there is an HTML Submit button inside the Form which when clicked, the Form is submitted and the file is downloaded.
Layout = null;
<meta name="viewport" content="width=device-width" />
@using (Html.BeginForm("Export", "Home", FormMethod.Post))
<input type="submit" name="name" value="Export" />
The generated XML file