How to return an XML string as an action result in MVC

.NetXmlasp.net MvcActionresult

.Net Problem Overview


> Possible Duplicate:
> What is the best way to return XML from a controller's action in ASP.NET MVC?

I'm able to return JSON and partial views (html) as a valid ActionResult, but how would one return an XML string?

.Net Solutions


Solution 1 - .Net

You could use return this.Content(xmlString, "text/xml"); to return a built XML string from an action.

Solution 2 - .Net

For JSON/XML I have written an XML/JSON Action Filter that makes it very easy to tackle without handling special cases in your action handler (which is what you seem to be doing).

Solution 3 - .Net

Another way to do this is by using XDocument:

using System.Xml.Linq;

public XDocument ExportXml()
{
    Response.AddHeader("Content-Type", "text/xml");

    return XDocument.Parse("<xml>...");
}

Solution 4 - .Net

If you're building the XML using Linq-to-XML then check out my answer here. It allows you to write code like this:

public ActionResult MyXmlAction()
{
    var xml = new XDocument(
        new XElement("root",
            new XAttribute("version", "2.0"),
            new XElement("child", "Hello World!")));

    return new XmlActionResult(xml);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionToran BillupsView Question on Stackoverflow
Solution 1 - .NetJohn DowneyView Answer on Stackoverflow
Solution 2 - .NetaleembView Answer on Stackoverflow
Solution 3 - .NetLevitikonView Answer on Stackoverflow
Solution 4 - .NetDrew NoakesView Answer on Stackoverflow