C# 无法在ASP.NET中将数据导出为XML-将数据导出为HTML而不是XML
我想将ASP.NET web表单应用程序中的一些数据导出到可下载的XML文件中,但无法将下载的信息显示为XML文件。它将信息输出为html文档而不是XMLC# 无法在ASP.NET中将数据导出为XML-将数据导出为HTML而不是XML,c#,asp.net,xml,C#,Asp.net,Xml,我想将ASP.NET web表单应用程序中的一些数据导出到可下载的XML文件中,但无法将下载的信息显示为XML文件。它将信息输出为html文档而不是XML protected void ExportXMLButton_Click(object sender, EventArgs e) { using (MemoryStream stream = new MemoryStream()) { // Create an XML document. Write our
protected void ExportXMLButton_Click(object sender, EventArgs e)
{
using (MemoryStream stream = new MemoryStream())
{
// Create an XML document. Write our specific values into the document.
XmlTextWriter xmlWriter = new XmlTextWriter(stream, System.Text.Encoding.ASCII);
// Write the XML document header.
xmlWriter.WriteStartDocument();
// Write our first XML header.
xmlWriter.WriteStartElement("WebApplications");
// Write an element representing a single web application object.
xmlWriter.WriteStartElement("WebApplication");
// Write child element data for our web application object.
xmlWriter.WriteElementString("Date", DateTime.Now.ToString());
xmlWriter.WriteElementString("Programmer", "Label1.Text");
xmlWriter.WriteElementString("Name", "Sample name ");
xmlWriter.WriteElementString("Language", "C# ");
xmlWriter.WriteElementString("Status", "Done");
// End the element WebApplication
xmlWriter.WriteEndElement();
// End the document WebApplications
xmlWriter.WriteEndElement();
// Finilize the XML document by writing any required closing tag.
xmlWriter.WriteEndDocument();
// To be safe, flush the document to the memory stream.
xmlWriter.Flush();
// Convert the memory stream to an array of bytes.
byte[] byteArray = stream.ToArray();
// Send the XML file to the web browser for download.
Response.Clear();
Response.AppendHeader("Content-Disposition", "filename=MyExportedFile.xml");
Response.AppendHeader("Content-Length", byteArray.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(byteArray);
xmlWriter.Close();
}
}
我希望输出是一个XML文件,但实际的输出是我的数据以文本形式显示在屏幕上。您写入了错误的标题。使用:
Content-Disposition: attachment;filename=...
Content-Type: application/xml
至少。见:
- 我认为删除这一点就是答案:
Response.AppendHeader("Content-Length", byteArray.Length.ToString());
Xml是文本!!!!这可能取决于浏览器处理XML文档的方式。例如,在我的开发机器上,firefox设置为下载XML文件,Chrome设置为在浏览器中显示它们。谢谢。但是,它现在显示为html文档,而不是XML文档,这可能取决于您的浏览器配置。