上传加载XML文件到XmlDocument对象 [英] Loading uploaded xml file into XmlDocument object

查看:244
本文介绍了上传加载XML文件到XmlDocument对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么可能是一个简单的问题道歉;七年后,没有我得到回编码。爱它,但一切都带我那么久!

Apologies for what might be a simple question; I'm getting back into coding after a seven year absence. Loving it, but everything is taking me so long!

无论如何,我试图从浏览器上传文件,然后读取到服务器上XmlDocument对象。本来我通过保存到磁盘文件,读取到XmlDocument对象,然后删除该文件破获这一点。唯一的问题是,删除操作试图完成了XMLDocument.load方法操作之前发生。
这感觉就像一个丑陋的解决方案,无论如何,所以它被遗弃愉快

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.

接下来的努力是直接从 Request.Files阅读[X] .InputStream 直接进入XmlDocument的,但我有问题。
下面的代码失败,出现缺少根元素的错误,但我知道XML是有效的,所以必须是别的东西。

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' error, but 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);
     }
}






你可以阅读有关在 http://ablesoftware.blogspot.com/

推荐答案

下面是一个例子:

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

和控制器动作:

[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();
}

这篇关于上传加载XML文件到XmlDocument对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆