2009-05-18 26 views
54

返回一個XML字符串作爲行動的結果可能重複:
What is the best way to return XML from a controller's action in ASP.NET MVC?如何在MVC

我能夠返回JSON和局部視圖(HTML)作爲一個有效的ActionResult ,但是如何返回一個XML字符串?

+0

在Codeplex上使用[MvcContrib](http://mvccontrib.codeplex.com)中的XmlResult。此外這似乎是一個[重複的問題](http://stackoverflow.com/questions/134905/what-is-the-best-way-to-return-xml-from-a-controllers-action-in-asp -net-MVC)。 – MotoWilliams 2009-05-18 19:10:18

回答

127

您可以使用return this.Content(xmlString, "text/xml");從操作中返回構建的XML字符串。

+0

很好的答案,謝謝 – Rippo 2010-10-29 08:43:04

+1

如果你正在使用Linq到XML,創建一個字符串形式的文檔是浪費 - 這是[最好使用流](http://stackoverflow.com/a/12718046/24874) 。 – 2012-10-04 08:31:56

7

對於JSON/XML我寫了一個XML/JSON Action Filter,這使得在處理動作處理程序時不需要處理特殊情況就很容易處理(這正是您所做的)。

+0

對於閱讀這篇文章的任何人 - 絕對檢查他的過濾器......它效果很好。 +1 to aleemb分享! – Mark 2010-09-09 05:58:25

4

另一種方式做,這是使用的XDocument:

using System.Xml.Linq; 

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

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

如果您正在構建使用XML Linq到XML,然後check out my answer here。它允許您編寫如下代碼:

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

    return new XmlActionResult(xml); 
}