How to return a XDocument generated XML file to browser?

I created a XML 1.0 file using XDocument class in .NET framework.

The question is: how do I return the generated file to the browser to allow the user to save it?

I have var generatedXMLfile = generateXml(Parameters param) this methods returns a XDocument class instance with my XML. Then I need to take the generatedXMLfile and return it to the browser as an XML file. I don't want to write a file in the server and then pass it to the browser, maybe it would be better to save a temp file in memory.

Thank You.

1 answer

  • answered 2020-03-31 09:26 Sean

    You need to convert it to a string and then return the string as an application/json content type.

    You can convert the document to a string like this:

    var sb = new StringBuilder();  
    var tr = new StringWriter(sb);  
    var xmlToSendToClient = sb.ToString();