Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading uploaded xml file into XmlDocument object

Anyway, I'm trying to upload a file from the browser and then read it into an XmlDocument object on the server. Originally I cracked this by saving the file to disk, reading it into the XmlDocument object and then deleting the file. The only problem was that the delete action was trying to take place before the XmlDocument.Load action had completed. It felt like an ugly solution anyway, so it was happily abandoned.

Next effort was to read directly from the Request.Files[x].InputStream directly into the XmlDocument, but I'm having problems. The following code fails with a

'Root element is missing'

I know the XML is valid so it must be something else.

foreach (string file in Request.Files) 
{
    HttpPostedFileBase postedFile = Request.Files[file] as  HttpPostedFileBase;

    if (postedFile.ContentLength > 0) //if file not empty
    {
       //create an XML object and load it in
        XmlDocument xmlProjPlan = new XmlDocument();

        Stream fileStream = postedFile.InputStream;
        byte[] byXML = new byte[postedFile.ContentLength];
        fileStream.Read(byXML, 0, postedFile.ContentLength);
        xmlProjPlan.Load(fileStream);
     }
}

like image 725
JonRed Avatar asked Dec 12 '22 20:12

JonRed


1 Answers

Here's an example:

<% using (Html.BeginForm("index", "home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
<% } %>

And the controller action:

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0 && file.ContentType == "text/xml")
    {
        var document = new XmlDocument();
        document.Load(file.InputStream);
        // TODO: work with the document here
    }
    return View();
}
like image 112
Darin Dimitrov Avatar answered Dec 15 '22 08:12

Darin Dimitrov