22 April 2011

ASP.NET - Output XML file

To download an XML file from an ASP.NET website, for instance after clicking a button, you can use the following sort of code. This one will retrieve a DataTable, and offer it as an XML file to download:

using (MemoryStream stream = new MemoryStream()) {
  XmlTextWriter xml = new XmlTextWriter(stream, Encoding.UTF8);
  xml.WriteStartDocument();
  xml.WriteStartElement("output");

  string value = string.Empty;
  foreach (DataRow row in data.Rows) {
    xml.WriteStartElement("row");
    foreach (DataColumn col in data.Columns) {
      value = row[col].ToString();
      xml.WriteElementString(col.ColumnName, value);
    }
    xml.WriteEndElement();
  }

  xml.WriteEndElement();
  xml.WriteEndDocument();
  xml.Flush();

  byte[] bytes = stream.ToArray();
  Response.Clear();
  Response.AppendHeader("Content-Disposition", "filename=Output.xml");
  Response.AppendHeader("Content-Length", bytes.Length.ToString());
  Response.ContentType = "application/octet-stream";
  Response.BinaryWrite(bytes);
  xml.Close();
}

No comments:

Post a Comment