0

I was wondering what is best way to create XML output from MVC2 application and return it to client ( possibly also using XSD scheme validation) ?

I know i can't return it directly from controller or pass to view as variable etc. Huge part of my application is doing conversion between different XML sources, schemas and formats so it's really important that I setup this right from the beginning.

But is there any better way to do it?

Thanks in advance!

2
  • Could you elaborate what you mean by 'XML rendered output'? (Do you want to display XML with colour formatting, indentation etc?) Commented Jun 27, 2011 at 12:30
  • oooh sorry, I see now it's little confusing Commented Jun 27, 2011 at 12:32

1 Answer 1

4

You could write a custom ActionResult which will serialize the view model into XML. Something among the lines:

public class XmlResult : ActionResult
{
    private readonly object _model;
    public XmlResult(object model)
    {
        _model = model;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (_model != null)
        {
            var response = context.HttpContext.Response;
            var serializer = new XmlSerializer(_model.GetType());
            response.ContentType = "text/xml";
            serializer.Serialize(response.OutputStream, _model);
        }
    }
}

and then:

public ActionResult Foo()
{
    SomeViewModel model = ...
    return new XmlResult(model);
}

Feel free to perform any XSD validations, etc... that you might need inside the ExecuteResult method.

As suggested by @Robert Koritnik in the comments section you could also write an extension method:

public static class ControllerExtensions
{
    public static ActionResult Xml(this ControllerBase controller, object model)
    {
        return new XmlResult(model);
    }
}

and then:

public ActionResult Foo()
{
    SomeViewModel model = ...
    return this.Xml(model);
}

This being said if you find yourself in the need of exchanging lots of XML you might consider using WCF. And if you need POX, consider WCF REST.

Sign up to request clarification or add additional context in comments.

3 Comments

I suggest to also add a controller extension method Xml() so it will be more in line with existing results. One would then simply write: return Xml(model); similar to other action results.
+1 here and deleting my own answer as yours popped up while I was adding it. I would add to @Robert's comment that support for either XmlSerializer or DataContractSerializer might be an idea.
@Robert Koritnik, nice suggestion, I've updated my answer to take it into account.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.