1

I'm trying to generate an XML document from C# List. The xml document must adhere to third party XML Schema.

I've had a look at XSD2CODE tool but did not get anywhere.

Could someone please help me with how to generate an XML file using LINQ to xml and return XML file using MVC3.

Nil Pun
  • 17,035
  • 39
  • 172
  • 294
  • Here is an example how to return XML sitemap instead of normal view if it helps your case, you can check it out [Sitemap](http://www.networkozone.com/snippets/c-sharp/7/asp-net-mvc-simple-sitemap) – formatc Jun 21 '12 at 13:21

2 Answers2

9

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

If you create an XDocument, add your XElements to it and then call the Save() method on the document it should create your file for you

Blog post showing how to create a file from XDocument

According to XDocument MSDN you can Save it to a stream or directly into a file. If you want to return it as an action you can look here How to return an XML string as an action result in MVC

Community
  • 1
  • 1
Dave
  • 2,552
  • 5
  • 25
  • 30