Nick V
Nick V

Reputation: 707

Download an XmlDocument

I just want to be able to press on a button and get an xmldocument file to download.

I've tried allot of things, for example:

XmlDocument doc As XmlDocument() = //Method that gets a xmldocument
Response.Clear()
this.Response.ContentType = "text/xml"
xmldoc.Save(this.Response.OutputStream)

and

Dim xmldocument As XmlDocument = //Method that gets a xmldocument
Using stream As MemoryStream = New MemoryStream()
            Dim xmlWriter As XmlTextWriter = New XmlTextWriter(stream, System.Text.Encoding.ASCII)
            xmldocument.WriteTo(xmlWriter)
            xmlWriter.Flush()

            Dim byteArray As Byte() = stream.ToArray()
            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()
        End Using

Nothing works, am i forgetting something obvious? because nothing works, the xmldocument is loaded everything seems fine but the file never downloads and the "response" does absolutely nothing!

An answer in Csharp or VB.NET would be helpfull

Upvotes: 0

Views: 5378

Answers (2)

Kami
Kami

Reputation: 19407

Try something like this

XmlDocument doc = new XmlDocument();
doc.LoadXml(@"
<root name='rootAttribute'>
    <OrderRequest name='one' />
    <OrderRequest name='two' />
    <OrderRequest name='three' />
</root>
"); // Load some random xml - use function to load whatever you need

MemoryStream ms = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(ms))
{
    doc.WriteTo(writer); // Write to memorystream
}

byte[] data = ms.ToArray();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.AddHeader("Content-Disposition:",
                    "attachment;filename=" + HttpUtility.UrlEncode("samplefile.xml")); // Replace with name here
HttpContext.Current.Response.BinaryWrite(data);
HttpContext.Current.Response.End();
ms.Flush(); // Probably not needed
ms.Close();

Upvotes: 2

Kevin
Kevin

Reputation: 704

Have you tried...

Response.ContentType = "text/xml"
Response.Write(MethodThatReturnsXMLDoc().innerXml)

Upvotes: 0

Related Questions