mark_spencer
mark_spencer

Reputation: 393

Create custom xml (ASP.NET MVC)

I have method to get all values from database

Here is code

public IQueryable<TimeTable> GetTimeTables()
    {
        return db.TimeTables;
    }

Here is model of TimeTable

public partial class TimeTable
{
    public int Id { get; set; }
    public string Company { get; set; }
    public string INN { get; set; }
    public string StartDay { get; set; }
    public string StartPause { get; set; }
    public string EndDay { get; set; }
    public string EndPause { get; set; }
}

I need to generate xml from values like this

<data>
<worker id="000000000000">
    <start>2016-08-08T08:00:00</start>
    <pause>2016-08-08T13:15:49</pause>
    <continue>2016-08-08T13:15:49</continue>
    <end>2016-08-08T13:15:49</end>
</worker>
<worker id="000000000001">
    <start>2016-08-08T08:00:00</start>
    <pause>2016-08-08T13:15:49</pause>
    <continue>2016-08-08T13:15:49</continue>
    <end>2016-08-08T13:15:49</end>
</worker>

Where id is INN, start is StartDay, pause is StartPause, continue is EndPause, end is EndDay.

How I can do this?

Upvotes: 0

Views: 1506

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239460

This is pretty straight-forward, so I'm not sure where exactly you're running into issues. Essentially, you just need to build an XDocument like:

var xdoc = new XDocument(
    new XElement("data",
        timeTables.Select(w =>
            new XElement("worker",
                new XAttribute("id", w.INN),
                new XElement("start", w.StartDay),
                new XElement("pause", w.StartPause),
                new XElement("continue", w.EndPause),
                new XElement("end", w.EndDay)
            )
        )
    )
);

Then, you just return this as a ContentResult with a mime type:

return Content(xdoc.ToString(), "application/xml", Encoding.UTF8);

Upvotes: 2

Related Questions