首页 > 解决方案 > 如何仅匹配上传的xml文件的指定xml标签

问题描述

我想上传只指定特定标签的 xml 文件。否则,上传失败。我正在使用 MVC 5 框架应用程序

这是我所做的。对于我的控制器,

[HttpPost]
public ActionResult Upload(HttpPostedFileBase xmlFile)
{
     if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
     {
          var xmlPath = Server.MapPath("~/XML/" + xmlFile.FileName);
          xmlFile.SaveAs(xmlPath);
          XDocument xDoc = XDocument.Load(xmlPath);

          List<Product> productList = xDoc.Descendants("product").Select(product => new Product
          {
               Id = Convert.ToInt32(product.Element("id").Value),
               Name = product.Element("name").Value,
               Price = Convert.ToDecimal(product.Element("price").Value),
               Quantity = Convert.ToInt32(product.Element("quantity").Value)
          }).ToList();

          using (testXMLEnt db = new testXMLEnt())
          {
               foreach (var i in productList)
               {
                    var v = db.Products.Where(a => a.Id.Equals(i.Id)).FirstOrDefault();

                    if (v != null)
                    {
                        v.Id = i.Id;
                        v.Name = i.Name;
                        v.Price = i.Price;
                        v.Quantity = i.Quantity;
                    }
                    else
                    {
                        db.Products.Add(i);
                    }
                        db.SaveChanges();
               }
          }
                ViewBag.Success = "File uploaded successfully..";
      }
      else
      {
          ViewBag.Error = "Invalid file(Upload xml file only)";
      }
      return View();
}

这是将要上传的两个不同的 xml 文件。文件1.xml

<customers>  
  <customer>  
    <id>1</id>  
    <name>Mobele Phone</name>  
    <price>12000</price>  
    <quantity>2</quantity>  
  </customer> 
</customers> 

文件2.xml

<products>  
  <product>  
    <id>1</id>  
    <name>Mobele Phone</name>  
    <price>12000</price>  
    <quantity>2</quantity>  
  </product>  

File1 和 File2 之间的区别是<customer><product>。如何指定成功上传的文件只会是带有标签的文件。否则,上传失败。

标签: c#sql-serverxmldatabaseasp.net-mvc-5

解决方案


推荐阅读