将数据导出为内存流中的 XML 并提供下载提示
如何即时生成 XML 内容,
以下代码片段演示了如何动态生成 XML 内容,然后将其存储在内存中(MemoryStream
)。如果无法在服务器上保存输出,或者避免处理权限问题,这种做法非常有用。相反,XML 在内存中生成,然后用户将自动提示将 XML 文件下载到本地资源,类似于尝试下载文件时发生的情况。
protected bool GenerateExportFile()
{
try
{
//Create Memory Stream to store XML Data
MemoryStream ms = new MemoryStream();
//Use a writer to create the XML
using (XmlWriter writer = XmlWriter.Create(ms))
{
writer.WriteStartDocument(); //Header
writer.WriteComment("Comment goes here");
{
writer.WriteStartElement("Root"); //<Root>
{
writer.WriteStartElement("Element1"); //<Element1>
writer.WriteAttributeString("Attribute1", "AtributeValue");
writer.WriteStartElement("Element2");
writer.WriteString("Element2Value");
writer.WriteEndElement(); //<Element2>
}
writer.WriteEndElement(); //<Root>
//Closed the Root Tag
}
writer.WriteEndDocument();
writer.Close();
//Convert Memory Stream to Byte Array
byte[] data = ms.ToArray();
//The Proposed FileName that will show when the
//user is prompted to save the file
string xmlFileName = "OrdExp_" + DateTime.Today.Year.ToString() +
DateTime.Today.Month.ToString("00") +
DateTime.Today.Day.ToString("00");
//Creating the Context
HttpContext.Current.Response.Clear();
//Heads up browser, here comes some XML
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.AddHeader("Content-Disposition:",
"attachment;filename=" + HttpUtility.UrlEncode(xmlFileName));
//Set the size of the file so the progress bar reports that correctly
HttpContext.Current.Response.AddHeader("Content-Length",
data.Length.ToString());
//Download the file and prompt the user to save
HttpContext.Current.Response.BinaryWrite(data);
HttpContext.Current.Response.End();
ms.Flush();
ms.Close();
return true;
}
}
catch (Exception exc)
{
lblMsg.Text = "Error Generating File: " + exc.Message;
return false;
}
return true;
}//Method
这段代码用于生成 XML 数据输出,然后添加了自动将数据导出到本地机器的功能。
希望这有帮助!
Will