ASP.NET MVC > Exporting Data

Export data into XML from MVC in ASP.NET MVC

How to export data into XML from ASP.NET MVC?


To export data into XML in ASP.NET, we can follow below approach.

CONTROLLER ACTION METHOD

public void ExportToXML()
       {
            var data = db.PersonalDetails.ToList();

            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;
filename=itfunda.xml");
            Response.ContentType = "text/xml";

            var serializer = new
System.Xml.Serialization.XmlSerializer(data.GetType());
            serializer.Serialize(Response.OutputStream, data);
       }

In the above action method, we are getting the data from the database and setting almost same properties of the Response object that we have set into previous post.

The changes are following

  • we are changing the name of the file to download
  • setting the ContentType to “text/xml”
  • using XmlSerializer to Serialize the data into XML and sending to the Response OutputStream.

Calling above method from browser like http://localhost:63087/ExportData/ExportToXML gives below output in which browser asks to Open or Save the xml file.

The output file looks like below

OUTPUT

 Views: 22054 | Post Order: 131



Write for us






Hosting Recommendations