LINQ to XML is used for querying XML, not generating. If you want to generate an XML file there are other techniques:
But no matter which XML generation technique you choose to adopt I would recommend you writing a custom action result that will perform this job instead of polluting your controller with XML generation plumbing which is absolutely not its responsibility.
Let's have an example using the third approach (XmlSerializer
).
Suppose that you have defined a view model that you want to convert to XML:
public class MyViewModel
{
public string Foo { get; set; }
public string Bar { get; set; }
}
Now we could write a custom action result that will perform this conversion:
public class XmlResult : ActionResult
{
public XmlResult(object data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
Data = data;
}
public object Data { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "text/xml";
var serializer = new XmlSerializer(Data.GetType());
serializer.Serialize(response.OutputStream, Data);
}
}
and the controller action will be pretty standard:
public ActionResult Index()
{
var model = new MyViewModel
{
Foo = "foo",
Bar = "bar"
};
return new XmlResult(model);
}
You might also want to check the ASP.NET MVC 4 Web API which makes those scenarios pretty easy.