0
Hello, I need your help again. I’m working on a project that consists of reading XML files and storing the data in a table. I can already do that, but I have a problem.
This is an example of an XML file.
<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>
This is the code to read that same file.
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;
}
This code works. Only one small problem is that it only reads the first Description. And I wanted him to read the two descriptions. It’s probably a simple change to make, but I have no ideas on how to run it.
I know that the ideal was to create two tables and then make the connection between them. But if you can help me read these two Oots, that’s enough.
Thank you!
two nodes with the same name is not very functional, it would be better to have
<descriptons><description>...</description><description>...</description></descriptions>
. This xml would not be deserialized correctly for a class– Ricardo Pontual
If you can change the XML structure, do as the colleague pointed out.
– Leandro Angelo
@Andre Managed to evolve?
– Leandro Angelo
@Leandroangelo not yet, I can not change the structure of XML, but I am trying otherwise.
– Andre