c# - 如何仅匹配上传的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>
。如何指定成功上传的文件只会是带有标签的文件。否则,上传失败。
解决方案
推荐阅读
- json - 在 GetX Flutter 中使用模型来解析 JSON 数据是一种好习惯吗?
- arrays - 如何检查结构中是否存在值?
- go - 您如何优雅地退出 go uber fx 应用程序
- javascript - 为什么 console.log(value) 返回一个空字符串?
- html - 在 HTML 中的 jpg 上调整和覆盖 SVG 图像
- python - 如何配对列表的每两个元素?
- perl - Perl - Mojolicious Webpack 无法从文件加载应用程序
- java - CAS 覆盖与 CAS 管理覆盖错误
- android - 如何在没有任何延迟的情况下在android中循环播放音频文件?
- attributes - 公共、受保护和私有属性可访问性