0

I upload an xml file through $.ajax post as formdata to an mvc controller. Is it possible to parse the file without it being saved in some directory in the server. My c# code is as below

        [HttpPost]
        public ActionResult VersionXML()
        {
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];
                /*--Can I exempt this if clause and do something for the parsing--*/
                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
                    file.SaveAs(path);
                }
            }

            return RedirectToAction("Show_New_Content");
        }
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
Arvin
  • 954
  • 3
  • 14
  • 33

1 Answers1

1

You have two options to parse with XML

1) You can load InputStream of your file to XmlDocument directly and process your xml,

if (file != null && file.ContentLength > 0 && file.ContentType == "text/xml")
{
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(file.InputStream);

    //You can parse your xml here

    //Upload file code here       
}

2) You can also load InputStream of your file to XDocument,

if (file != null && file.ContentLength > 0 && file.ContentType == "text/xml")
{
    XDocument doc = XDocument.Load(new StreamReader(file.InputStream));

    //You can parse your xml here

    //Upload file code here       
}
er-sho
  • 9,581
  • 2
  • 13
  • 26
  • Thanks.. may I know what exatly the difference in working of both these code? – Arvin Feb 07 '19 at 06:51
  • With `XDocument` you can use Linq on it and `XmlDocument` you can parse your xml in traditional. – er-sho Feb 07 '19 at 06:56
  • 1
    you can read more from here => https://stackoverflow.com/a/1542101/5514820, and https://social.msdn.microsoft.com/Forums/en-US/0d68f2bb-2195-4494-b0b1-54dc78aa56f0/xdocument-or-xmldocument?forum=xmlandnetfx – er-sho Feb 07 '19 at 06:57
  • @Arvin, I think you forgot to view my answer. If it helps then mark the tick on left side of the answer to make it green :) – er-sho Apr 09 '19 at 06:02