无论如何,我正在尝试从浏览器上传文件,然后将其读入服务器上的 XmlDocument 对象。最初我通过将文件保存到磁盘、将其读入 XmlDocument 对象然后删除文件来破解此问题。唯一的问题是删除操作试图在 XmlDocument.Load
操作完成之前发生。
无论如何,这感觉像是一个丑陋的解决方案,所以它很高兴地被放弃了。
接下来的工作是直接从 Request.Files[x].InputStream
读取到 XmlDocument,但我遇到了问题。
以下代码失败并显示
'Root element is missing'
我知道 XML 是有效的,所以它一定是其他东西。
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);
}
}
最佳答案
这是一个例子:
<% using (Html.BeginForm("index", "home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
<input type="file" name="file" />
<input type="submit" value="Upload" />
<% } %>
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();
}
关于c# - 将上传的 xml 文件加载到 XmlDocument 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3342998/