56

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?

Community
  • 1
  • 1
Toran Billups
  • 27,111
  • 40
  • 155
  • 268
  • Use the XmlResult from [MvcContrib](http://mvccontrib.codeplex.com) on Codeplex. Also this seems to be a [duplicate question](http://stackoverflow.com/questions/134905/what-is-the-best-way-to-return-xml-from-a-controllers-action-in-asp-net-mvc). – MotoWilliams May 18 '09 at 19:10

4 Answers4

131

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

John Downey
  • 13,854
  • 5
  • 37
  • 33
  • 1
    If you're working with Linq to XML, creating a string form of the document is wasteful -- it's [better to work with streams](http://stackoverflow.com/a/12718046/24874). – Drew Noakes Oct 04 '12 at 08:31
7

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).

aleemb
  • 31,265
  • 19
  • 98
  • 114
  • For anyone reading this post - definately check out his filter... it works well. +1 to aleemb for sharing! – Mark Sep 09 '10 at 05:58
4

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);
}
Community
  • 1
  • 1
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
4

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>...");
}
Levitikon
  • 7,749
  • 9
  • 56
  • 74
  • Some experimentation in MVC 4 (and possibly earlier versions) suggests that the MIME type returned here is `text/html`. – Drew Noakes Oct 03 '12 at 21:40