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
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