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.
No comments:
Post a Comment