Asp.Net - Read Files

Asked

Viewed 43 times

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!

  • 2

    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

  • If you can change the XML structure, do as the colleague pointed out.

  • @Andre Managed to evolve?

  • @Leandroangelo not yet, I can not change the structure of XML, but I am trying otherwise.

1 answer

0

You can join the descriptions using the method Join() string class. I modified your code to demonstrate below:

using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
    
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
    public string Description { get; set; }
}

public class Program
{
    static List<Product> db = new List<Product>(); //apenas para siMular dados incluídos no DbSet de produtos
    
    public static void Main()
    {
        ProcessImport("");
    }
    
    private static List<Product> ProcessImport(string path)
    {
    //XDocument xDocument = XDocument.Load(path);
        XDocument xDocument= new XDocument(  
            new XElement("products",  
                new XElement("product",
                    new XElement("id", "1"),
                    new XElement("name", "Ball"),  
                    new XElement("price", "15"),  
                    new XElement("quantity", "2"),  
                    new XElement("description",
                        new XElement("comment", "aaa")),  
                    new XElement("description",
                        new XElement("comment", "bbb")),   
                    new XElement("age", 
                        new XElement("number", "12"))  
                    )
            )  
        ); 
        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.ToDouble(p.Element("price").Value),
               Description = string.Join(",", p.Descendants("description").Select(a => a.Element("comment").Value))
            }).ToList();

        foreach(var product in products)
        {
            //var productInfo = db.Products.SingleOrDefault(p => p.Id.Equals(product.Id));
            var productInfo = db.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.Add(product);
            }

            //db.SaveChanges();
            Console.WriteLine("Produto: " + db[db.Count - 1].Name + " Descrição:  " + db[db.Count - 1].Description + " -> incluído com sucesso");
        }

        return products;
    }
}

You can see it running on Fiddler clicking here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.