Writing an XML file in ASP.NET MVC?

时间:2017-09-28 10:26:23

标签: c# asp.net xml asp.net-mvc

I have absolutely no experience with XML, let alone generating XML files, and I'm completely stuck.

I couldn't find any MVC related threads about this, just WPF and console.

I think I have a working code to generate a file judging by MSDN's guide之外的html正文中的所有HTML标记,但我不知道如何从MVC中继续前进,因为这是对于控制台。

这是在存储库中:

public void SaveFile(string fileName)
    {
        Checker checker = new Checker();
        XMLWriter xmlWriter = new XMLWriter();

        string userid = xmlWriter.UserId.ToString();
        string date = xmlWriter.Date;
        int hours = xmlWriter.Hours;
        string role = xmlWriter.Role;

        userid = checker.User.UserName;
        date = checker.Date.ToString();
        hours = int.Parse(checker.Total.ToString());
        role = checker.User.Roles.ToString();

        XDocument doc = new XDocument(
            new XElement("Tidrans",
                new XElement("tidkod", role),
                new XElement("datum", date),
                new XElement("timmar", hours)
            )
        );
        doc.Save("Test.xml");

    }

这是在模型中:

public class XMLWriter
{
    [Key]
    public int Id { get; set; }

    [Display(Name = "anstid")]
    public int UserId { get; set; }

    [Display(Name = "tidkod")]
    public string Role { get; set; }

    [Display(Name = "datum")]
    public string Date { get; set; }

    [Display(Name = "timmar")]
    public int Hours { get; set; }

    [Display(Name = "frånvarande")]
    public float Absent { get; set; }
}

我不知道如何去那里,我如何使用控制器?我需要控制器吗?我该如何下载?

4 个答案:

答案 0 :(得分:3)

我想你想要下载xml。如果是这种情况,请尝试以下代码:

    public FileStreamResult GenerateXML()
    {
        MemoryStream ms = new MemoryStream();
        XmlWriterSettings xws = new XmlWriterSettings();
        xws.OmitXmlDeclaration = true;
        xws.Indent = true;

        using (XmlWriter xw = XmlWriter.Create(ms, xws))
        {
            XDocument doc = new XDocument(
             new XElement("Tidrans",
              new XElement("tidkod", "role"),
              new XElement("datum", "date"),
              new XElement("timmar", "hours")
             )
            );
            doc.WriteTo(xw);
        }
        ms.Position = 0;
        return File(ms, "text/xml", "Sample.xml");
    }

以下是输出:

<Tidrans>
  <tidkod>role</tidkod>
  <datum>date</datum>
  <timmar>hours</timmar>
</Tidrans>

答案 1 :(得分:1)

您需要确定如何处理此问题。根据您已有的方法,您需要做的就是“运行”它。它可以是执行此操作的控制器操作,控制台应用程序,Azure功能等。可能性是无穷无尽的。运行后,您可以通过IIS直接提供XML文件。你甚至不需要MVC,因为那时它只是一个静态文件。

但是,如果你想动态生成它,那就是控制器动作可以发挥作用的地方。然后,您可以在该操作中调用此方法并直接返回创建的文件:

return File("Test.xml", "application/xml");

或者您可以让该方法实际上是您的操作本身的内容,并直接返回XML而不保存到文件系统:

return Content(doc.ToString(), "application/xml");

答案 2 :(得分:1)

这大概是最简单但最有效的返回XML内容的方式:

public ActionResult XmlData()
{
    var doc = new XDocument(
        new XElement("Root",
            new XElement("Node1", 1),
            new XElement("Node2", 2)
        )
    );

    Response.ContentType = "text/xml";

    doc.Save(Response.Output);

    return new EmptyResult();
}

如果您的XML文档足够大,则可以通过取消XDocument并直接写入响应流来简化输出。

答案 3 :(得分:-2)

[HttpPost]
public ActionResult Upisi(string reg, string datum, string startPos, string krajPos, string predjKm) {
    // upisivanje u fajl
    List<vozilo> vozila = TempData["vozila"] as List<vozilo>;
    List<voziloPodatak> ispis = new List<voziloPodatak>();

    string marka = "";
    string godina = "";
    int kilometri = 0;

    foreach (vozilo voz in vozila) {
        if (voz.Registracija == reg) {
            marka = voz.Model;
            godina = voz.Godiste;
        }
    }

    StreamWriter sw = new StreamWriter(Server.MapPath("~/App_Data/" + reg + ".txt"), true);       

    sw.WriteLine(datum + "|" + startPos + "|" + krajPos + "|" + predjKm);

    sw.Close();

    foreach (vozilo voz in vozila) {
        voziloPodatak podatak = new voziloPodatak();
        bool postoji = System.IO.File.Exists(Server.MapPath("~/App_Data/" + voz.Registracija + ".txt"));
        if (postoji)
        {
            podatak.Registracija = voz.Registracija;
            podatak.Marka = voz.Model;
            podatak.GodinaProizvodnje = voz.Godiste;

                using (StreamReader sr = new StreamReader(Server.MapPath("~/App_Data/" + voz.Registracija + ".txt")))
                {

                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] linija = line.Split('|');
                        int predjenoKmFajl = Convert.ToInt32(linija[3]);
                        kilometri += predjenoKmFajl;
                    }

                }
                podatak.PredjenoKilometara = kilometri.ToString();                

            ispis.Add(podatak);
        }
    }       
    return View(ispis);
}