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.

1
  • Here is an example how to return XML sitemap instead of normal view if it helps your case, you can check it out Sitemap Commented Jun 21, 2012 at 13:21

2 Answers 2

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.

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

Comments

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

Comments

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.