c# - Asp.Net Core - 读取文件
问题描述
我再次需要你的帮助。我一直在 asp.net 上做一个项目,我有一些疑问。
该项目包括读取 xml 文件并将数据保存在数据库中。我能够读取数据,但现在我有一个问题问题是......
我有这个 xml 文件。
-<products>
-<product>
<name>Ball</name>
<price>15</price>
<quantity>2</quantity>
-<description>
<comment>aaa</comment>
</description>
-<description>
<comment>bbb</comment>
</description>
-<age>
<number>12</number>
</age>
</product>
</products>
这就是程序。
private List<Product> ProcessImport(string path)
{
XDocument xDocument = XDocument.Load(path);
List<Product> products = xDocument.Descendants("product").Select
(p => new Product()
{
Id = Convert.ToInt32(p.Element("id").Value),
Name=p.Element("name").Value,
Quantity = Convert.ToInt32(p.Element("quantity").Value),
Price = Convert.ToInt32(p.Element("price").Value),
Description = p.Element("description").Element("comment")
}).ToList();
foreach(var product in products)
{
var productInfo = db.Products.SingleOrDefault(p => p.Id.Equals(product.Id));
if (productInfo != null)
{
productInfo.Id = product.Id;
productInfo.Name = product.Name;
productInfo.Quantity = product.Quantity;
productInfo.Price = product.Price;
productInfo.Description= product.Description;
}
else
{
db.Products.Add(product);
}
db.SaveChanges();
}
return products;
}
我的问题是,上面的程序只读取第一个描述。
我必须插入什么才能让他阅读这两个描述?(我认为理想的做法是创建两个表,然后在它们之间建立连接)
但现在我需要帮助来完成这项工作。
谢谢!!
解决方案
请注意,您的 xml 文件不包含id
节点,但您需要id
在方法中读取节点数据。ProcessImport
如果不包含id
节点,则无法读取代码中的数据。
根据您的要求,这是一个工作演示:
模型:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
public Description[] Description { get; set; }
}
public class Description
{
public string Comment { get; set; }
}
控制器:
private List<Product> ProcessImport()
{
XDocument xDocument = XDocument.Load("test.xml");
List<Product> products = xDocument.Descendants("product").Select
(p => new Product()
{
Id = Convert.ToInt32(p.Element("id").Value),
Name = p.Element("name").Value,
Quantity = Convert.ToInt32(p.Element("quantity").Value),
Price = Convert.ToInt32(p.Element("price").Value),
Description = p.Descendants("description").Select(d => new Description()
{
Comment = d.Element("comment").Value
}).ToArray()
}).ToList();
//do your stuff...
return products;
}
<?xml version="1.0" encoding="utf-8" ?>
<products>
<product>
<id>100</id>
<name>Ball</name>
<price>15</price>
<quantity>2</quantity>
<description>
<comment>aaa</comment>
</description>
<description>
<comment>bbb</comment>
</description>
<age>
<number>12</number>
</age>
</product>
</products>
推荐阅读
- c# - 一名开发人员;需要离线开发的统一 nuget
- reactjs - React 可以用 URL 填写页面信息吗?
- android - Hilt 正在将公共字段转换为私有字段并且无法注入
- reactjs - Formik & 是的 | 多文件上传验证
- maven - 嗨,我已经安装了 JDK 16.0.1 版本,并且在 eclipse 中我创建了一个 maven 项目,我想添加黄瓜依赖项
- java - 如何使用 Java 在 SQL 数据库中存储多维数组?
- javascript - Puppeteer - 找不到选择器的节点
- typescript - 如何 console.log 打字稿类型
- keyboard - 在没有管理员权限的情况下重新映射密钥
- python - IBM Db2 SQL Alchemy 适配器——客户端驱动程序问题