简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM