How to create a downloadable file created using XmlDocument ()

I created a file with

XmlDocument xmldoc = new XmlDocument();

Can I make this file downloadable? without saving?

+3
source share
5 answers

You can do something like:

XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<xml>myxml</xml>");
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=MyXmlDocument.xml");
Response.AddHeader("Content-Length", doc.OuterXml.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Write(doc.OuterXml);
+3
source

Here's how to do it:

xmldoc.Save(Response.OutputStream)

Remember to set the mime response type and other appropriate properties so that the client browser understands this as a file upload.

+1
source

Custom HTTP Handler (, IHttpHandler) web.config. . MSDN , .

, , XmlDocument.

using System.Web;

public class MyXmlDocumentHandler : IHttpHandler
{
    public static XmlDocument XmlDoc
    {
        get;
        set;
    }

    public MyXmlDocumentHandler()
    {
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/xml"; // Set the MIME type.
        XmlDoc.WriteTo(context.Response.OutputStream); // Write the XML markup to the respone stream.
    }

    public bool IsReusable
    {
        // To enable pooling, return true here.
        // This keeps the handler in memory.
        get { return false; }
    }
}
0

, , HTTP.

XML-, XmlDocument, , text/xml.

:

XmlDocument xmldoc = new XmlDocument();

/*
 * ... more code ...
 */

this.Response.ContentType = "text/xml";

xmldoc.Save(this.Response.OutputStream);
0

, . , - XmlDocument - (, ), , ( ).

Page :

xmldoc.Save(Response.OutputStream);

xmldoc.Save(Response.Output);

You can easily create an .ashx file and its associated code (the new "Common Handler" element), and then in the code that implements the IHttpHandlerimplementation ProcessRequestusing

public void ProcessRequest(HttpContext context)
{
    XmlDocument doc = ...;

    doc.Save(context.Response.OutputStream);
}

You can also set the appropriate type of content (possibly "text / xml", unless it matches a specific XML format that you want to interpret differently), etc. If you want the client to save it by default, you must set the content placement.

0
source

Source: https://habr.com/ru/post/1708805/


All Articles